package com.cnd3b.utility.obs.mpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.huawei.mpc.client.MpcClient;
import com.huawei.mpc.client.MpcConfig;
import com.huawei.mpc.model.ObsObjInfo;
import com.huawei.mpc.model.extract.CreateExtractTaskReq;
import com.huawei.mpc.model.extract.CreateExtractTaskRsp;
import com.huawei.mpc.model.transcoding.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MpcFactory {
    MpcConfig mpcConfig = null;

    public MpcFactory() {
        mpcConfig = new MpcConfig();
        mpcConfig.setEndPoint("mpc.cn-east-2.myhuaweicloud.com");// 设置转码节点地址
        mpcConfig.setProjectId("0770870e5900265f2f60c00b589e3ff6");// 设置用户项目编号ProjectId
        //mpcConfig.setSk(parameter.Bucket_sk());// 设置sk
        //mpcConfig.setAk(parameter.Bucket_ak());// 设置ak

        mpcConfig.setSk("9EUAXeFmxKjJ5x12lYVTzCCUuIQIjrO6VAyzGr9u");// 设置sk
        mpcConfig.setAk("EKJMDXUVJLBGDRCVVVLP");// 设置ak
    }


    public String createMpcTask(String bucketname, String filename) {
        bucketname = bucketname.toLowerCase();
        // 媒体处理服务构造方法
        MpcClient mpcClient = new MpcClient(mpcConfig);
        //设置媒体处理服务请求参数
        CreateTranscodingRequest createTranscodingRequest = new CreateTranscodingRequest();

        //设置转码源文件地址
        ObsObjInfo input = new ObsObjInfo();
        input.setBucket(bucketname);
        input.setObject(filename);
        input.setLocation("cn-east-2");
        createTranscodingRequest.setInput(input);


        // 设置转码后的文件存放地址
        ObsObjInfo output = new ObsObjInfo();
        output.setBucket(bucketname);
        output.setObject(filename + "-hls");
        output.setLocation("cn-east-2");
        createTranscodingRequest.setOutput(output);

        /*
        // 可选，设置水印功能（该设置需要启动水印功能时才进行设置）
        CreateTranscodingRequest.Watermark watermark = new CreateTranscodingRequest.Watermark();
        watermark.setTemplateId("watermark_template_id");
        // 设置水印图片地址
        ObsObjInfo watermarkInput  = new ObsObjInfo();
        watermarkInput.setBucket("bucketName");
        watermarkInput.setObject("objectKey");
        watermarkInput.setLocation("cn-north-4");
        watermark.setInput(watermarkInput);


        List<CreateTranscodingRequest.Watermark> watermarks = new ArrayList<CreateTranscodingRequest.Watermark>();
        watermarks.add(watermark);

        CreateTranscodingRequest.Watermark[] watermarkArray = new CreateTranscodingRequest.Watermark[watermarks.size()];
        createTranscodingRequest.setWatermarks(watermarks.toArray(watermarkArray));
        */

        //设置转码模板ID
        List<Long> transTempIds = new ArrayList<Long>();
        transTempIds.add(7000494L);
        createTranscodingRequest.setTransTemplateId(transTempIds);

        /*
         // 设置截图参数（该设置需要截图时才进行设置）
         CreateTranscodingRequest.Thumbnail thumbnail = new CreateTranscodingRequest.Thumbnail();
         //设置截图文件打包方式，此处为tar包形式
         thumbnail.setTar(1);
         //设置截图源文件地址,需确认已对媒体处理服务进行桶授权
         ObsObjInfo thumbOutput = new ObsObjInfo();
         //OBS桶名
         thumbOutput.setBucket("obs-bills");
         //OBS桶所在区域
         thumbOutput.setLocation("cn-north-4");
         //OBS桶下存放路径
         thumbOutput.setObject("output/thumbnail/");
         thumbnail.setThumbOutput(thumbOutput);
         CreateThumbnailRequest.ThumbnailPara thumbnailPara = new CreateThumbnailRequest.ThumbnailPara();
         //采样类型。支持三种采样方式PERCENT、TIME和DOTS(根据时间间隔time，根据视频时长百分比percent，根据时间截图时的时间点数组dots，目前只支持TIME和DOTS两种方式)
         thumbnailPara.setTime(12);
         //设置最大长度
         thumbnailPara.setMaxLength(480);
         //设置纵横比
         thumbnailPara.setAspectRatio(0);
         //设置截图格式，0表示默认，1表示JPG格式
         thumbnailPara.setFormat(1);
         createTranscodingRequest.setThumbnail(thumbnail);
         */

        /*
       //设置转码优先级 6：中优先级（默认为当前优先级）；9：高优先级
        createTranscodingRequest.setPriority(6);
        */

       /*
       //设置字幕参数
       CreateTranscodingRequest.Subtitle subtitle = new CreateTranscodingRequest.Subtitle();
       //设置字幕类型 0：不输出字幕 ；1：外部字幕文件嵌入视频
       subtitle.setSubtitleType(1);
       //设置字幕文件地址
       ObsObjInfo fileInput = new ObsObjInfo();
       fileInput.setBucket("bucketName");
       fileInput.setObject("objectKey");
       fileInput.setLocation("cn-north-4");
       subtitle.setSubtitleFile(fileInput);
       createTranscodingRequest.setSubtitle(subtitle);
       */
/*
        // 设置加密参数
        CreateTranscodingRequest.Encryption encryption = new CreateTranscodingRequest.Encryption();
        CreateTranscodingRequest.Encryption.Multidrm multidrm = new CreateTranscodingRequest.Encryption.Multidrm();
        //设置content_id唯一标识
        multidrm.setContentId("contentId");
        //定义数据流的类型，取值为DASH或HLS
        multidrm.setStreamingMode("HLS");
        //音频加密开关（0：标识音频不加密；1：标识音频加密；默认0）
        multidrm.setEncryptAudio(1);
        //定义加密方式，取值包括：默认为16420
        multidrm.setEmi(16420);
        multidrm.setDrmList(new String[]{"PLAYREADY"});
        encryption.setMultidrm(multidrm);
        createTranscodingRequest.setEncryption(encryption);
*/
        /*
        // 设置图像旋转参数
        VideoProcess videoProcess = new VideoProcess();
        // 视频顺时针旋转角度，可取值为0,1,2,3。0表示不旋转，1表示顺时针旋转90度，2表示顺时针旋转180度，3表示顺时针旋转270度.
        videoProcess.setRotate(2);
        createTranscodingRequest.setVideoProcess(videoProcess);
*/
        // 设置画质增强参数
        QualityEnhance qualityEnhance = new QualityEnhance();
        // 针对一般质量、无明显问题的普通片源，通过增强、锐化等技术明显提升主观效果。该处理操作前后，分辨率、帧率等参数不发生变化。
        qualityEnhance.setNormalEnhance(QualityEnhance.NormalEnhanceEnum.NORMAL);
        createTranscodingRequest.setQualityEnhance(qualityEnhance);

        // 设置音量调节参数
        AudioProcess audioProcess = new AudioProcess();
        // 音量调整方式，可取值为auto和dynamic：auto表示自动调整音量。dynamic表示人为调整，需设定音量调整幅值。
        audioProcess.setVolume(AudioProcess.VolumeEnum.DYNAMIC);
        // 音量调整幅值，范围[-15,15],单位：dB （需指定volume为dynamic）。
        audioProcess.setVolumeExpr(15);
        createTranscodingRequest.setAudioProcess(audioProcess);

        //发送媒体处理服务请求
        CreateTranscodingResponse createTranscodingResponse = mpcClient.createTranscodingTask(createTranscodingRequest);
        //返回消息
        String taskId = "";
        JSONObject resultObject = (JSONObject) JSON.toJSON(createTranscodingResponse);
        if (resultObject.containsKey("requestStatus") && "SUCCESS".equalsIgnoreCase(resultObject.getString("requestStatus"))) {
            taskId = resultObject.getString("taskId");
        }
        return taskId;
    }

    public MpcFile queryMpcTask(String taskId) {
        //媒体处理服务构造方法
        MpcClient mpcClient = new MpcClient(mpcConfig);

        //设置查询转码任务参数
        QueryTranscodingRequest queryTranscodingRequest = new QueryTranscodingRequest();

        //查询多个转码任务，多个转码任务ID，一次最多只能查询10个
        String[] taskIds = {taskId};
        //设置多个查询转码任务ID
        queryTranscodingRequest.setTaskIdArray(taskIds);

        /**
         * According to the status query
         */
        /*String status="CANCELED";
        //根据转码任务状态查询，设置转码任务状态
        queryTranscodingRequest.setStatus(status);*/

        /**
         * According to the page&size query,If you do not provide default display 10 data
         */
        //根据页码和每页条数查询
        //设置页码
        /*queryTranscodingRequest.setPage(0);
        //设置每页条数
        queryTranscodingRequest.setSize(4);*/

        /**
         * According to the startTime&endTime query
         */
        //根据转码任务开始和结束时间查询
        //设置转码任务开始时间
        /*queryTranscodingRequest.setStartTime("20180116125625");
        //设置转码任务结束时间
        queryTranscodingRequest.setEndTime("20180118132810");*/

        //发送查询转码任务请求
        QueryTranscodingResponse queryTranscodingResponse = mpcClient.queryTranscodingTask(queryTranscodingRequest);

        /*response*/
        //返回查询转码任务结果
        JSONObject resultObject = JSON.parseObject(new Gson().toJson(queryTranscodingResponse));

        if (resultObject.containsKey("requestStatus") && "SUCCESS".equalsIgnoreCase(resultObject.getString("requestStatus"))) {
            if (resultObject.containsKey("task_array")) {
                JSONArray task_array = resultObject.getJSONArray("task_array");
                for (Object o : task_array) {
                    JSONObject object = (JSONObject) o;
                    if (taskId.equalsIgnoreCase(object.getString("task_id"))) {
                        MpcFile mpcFile = new MpcFile();
                        mpcFile.setTask_id(taskId);
                        if((object.getJSONArray("output_file_name").isEmpty())){
                            return null;
                        }else {
                            mpcFile.setOutput_file_name(object.getJSONArray("output_file_name").getString(0));
                        }
                        JSONObject outputObject = object.getJSONObject("output");
                        mpcFile.setBucket(outputObject.getString("bucket"));
                        mpcFile.setLocation(outputObject.getString("location"));
                        mpcFile.setObject(outputObject.getString("object"));
                        return mpcFile;
                    }
                }
            }
        }
        return null;
    }

//    public void deleteMpcTask(String taskId) {
//        MpcClient mpcClient = new MpcClient(mpcConfig);
//        BaseResponse baseResponse = mpcClient.deleteTranscodingTask(taskId);
//        JSONObject resultObject = (JSONObject) JSON.toJSON(baseResponse);
//    }

    public MediaMetaData getMetaData(String bucketname, String filename) {
        bucketname = bucketname.toLowerCase();
        MediaMetaData mediaMetaData = new MediaMetaData();
        MpcClient mpcClient = new MpcClient(mpcConfig);
        CreateExtractTaskReq req = new CreateExtractTaskReq();

        ObsObjInfo input = new ObsObjInfo();
        input.setBucket(bucketname);
        input.setLocation("cn-east-2");
        input.setObject(filename);
        req.setInput(input);
        try {
            // 发起请求
            CreateExtractTaskRsp rsp = mpcClient.createExtractTask(req);
            JSONObject resultObject = (JSONObject) JSON.toJSON(rsp);
            System.err.println(resultObject);
            if ("SUCCESS".equalsIgnoreCase(resultObject.getString("requestStatus")) && "SUCCEED".equalsIgnoreCase(resultObject.getString("status"))) {
                JSONObject metadataObject = resultObject.getJSONObject("metadata");

                mediaMetaData.setSize(metadataObject.getLongValue("size"));
                mediaMetaData.setFormat(metadataObject.getString("format"));
                mediaMetaData.setStatus(true);

                if (metadataObject.containsKey("video")) {
                    JSONArray videoArray = metadataObject.getJSONArray("video");
                    Iterator it = videoArray.iterator();
                    while (it.hasNext()) {
                        JSONObject videoObjcet =(JSONObject) it.next();
                        mediaMetaData.setCodec(videoObjcet.getString("codec"));
                        mediaMetaData.setFrameRate(videoObjcet.getIntValue("frameRate"));
                        mediaMetaData.setWidth(videoObjcet.getIntValue("width"));
                        mediaMetaData.setHeight(videoObjcet.getIntValue("height"));
                        mediaMetaData.setBitrate(videoObjcet.getLongValue("bitrate"));
                    }
                }
            } else {
                mediaMetaData.setStatus(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mediaMetaData;
    }

    public static void main(String[] args) {
        MpcFactory mpcFactory = new MpcFactory();
        mpcFactory.getMetaData("jxyl", "202104231619140535806B4e81fa83.mp4");
    }
}
