package com.wisewoods.eduandroid.oss;


import android.app.Activity;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.Utils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.app.PictureAppMaster;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.MediaUtils;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.qcloud.core.auth.BasicLifecycleCredentialProvider;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.QCloudLifecycleCredentials;
import com.tencent.qcloud.core.auth.SessionQCloudCredentials;
import com.tencent.qcloud.core.common.QCloudClientException;
import com.wisewoods.base.bean.CosInfo;
import com.wisewoods.base.utils.GlideEngine;
import com.wisewoods.eduandroid.app.App;

import java.io.IOException;
import java.util.List;

import retrofit2.Response;

public class OSSManager implements ICloundOS {

    public static final String OSSPATH = "edu_android/";


    public static class MySessionCredentialProvider extends BasicLifecycleCredentialProvider {
        @Override
        protected QCloudLifecycleCredentials fetchNewCredentials()
                throws QCloudClientException {

            try {
                Response<CosInfo> data = App.api.getCosInfo().execute();
                CosInfo cosInfo = data.body();
                return new SessionQCloudCredentials(cosInfo.data.credentials.tmpSecretId,
                        cosInfo.data.credentials.tmpSecretKey,
                        cosInfo.data.credentials.sessionToken,
                        cosInfo.data.startTime,
                        cosInfo.data.expiredTime);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

        }
    }

    private static OSSManager sInstance;
    private final TransferManager transferManager;
    private String bucket;

    public static synchronized OSSManager getInstance() {
        if (sInstance == null) {
            sInstance = new OSSManager();
        }
        return sInstance;
    }

    private OSSManager() {
        QCloudCredentialProvider provider = new MySessionCredentialProvider();
        String region = "ap-beijing";
        CosXmlServiceConfig serviceConfig = new CosXmlServiceConfig.Builder()
                .setRegion(region)
                .isHttps(true) // 使用 HTTPS 请求, 默认为 HTTP 请求
                .builder();
        CosXmlService cosXmlService = new CosXmlService(Utils.getApp(), serviceConfig, provider);
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        transferManager = new TransferManager(cosXmlService, transferConfig);

        bucket = "college-file-1302740389";
    }


    @Override
    public void upload(String dir, String filePath, ICloundOS.Callback callback) {

        String cosPath = dir;

        // 若存在初始化分块上传的 UploadId，则赋值对应的 uploadId 值用于续传；否则，赋值 null。
        // 当次上传任务的 uploadid 可以在 TransferStateListener 的回调中拿到
        String uploadId = null;
        // 上传文件
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath, filePath, uploadId);
        //设置上传进度回调
        cosxmlUploadTask.setCosXmlProgressListener((complete, target) -> {
            if (callback != null && callback instanceof ProgressCallback) {
                ThreadUtils.runOnUiThread(() -> {
                    ((ProgressCallback) callback).progress(complete, target);
                });
            }
        });
        //设置返回结果回调
        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult =
                        (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                String accessUrl = cOSXMLUploadTaskResult.accessUrl;
                if (callback != null) {
                    ThreadUtils.runOnUiThread(() -> {
                        callback.call(ICloundOS.CODE_SUCCESS, accessUrl);
                    });
                }
            }

            @Override
            public void onFail(CosXmlRequest request,
                               CosXmlClientException clientException,
                               CosXmlServiceException serviceException) {
                String msg;
                if (clientException != null) {
                    msg = clientException.getMessage();
                    clientException.printStackTrace();
                } else {
                    msg = serviceException.getMessage();
                    serviceException.printStackTrace();
                }
                if (callback != null) {
                    ThreadUtils.runOnUiThread(() -> {
                        callback.call(ICloundOS.CODE_ERROR, msg);
                    });
                }
            }
        });
    }

    @Override
    public void download() {

    }

    public void selectAvater(Activity activity, String dir, Callback callback) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .selectionMode(PictureConfig.SINGLE)
                .isEnableCrop(true)
                .circleDimmedLayer(true)
                .showCropGrid(false)
                .showCropFrame(false)
                .isCompress(true)
                .withAspectRatio(1, 1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {

                    @Override
                    public void onResult(List<LocalMedia> result) {
                        String mCoverImagePath = "";
                        if (result.get(0).isCompressed()) {
                            mCoverImagePath = result.get(0).getCompressPath();
                        } else {
                            mCoverImagePath = result.get(0).getRealPath();
                        }
                        String name = FileUtils.getFileName(mCoverImagePath);
                        upload(dir+name, mCoverImagePath, callback);
                    }

                    @Override
                    public void onCancel() {
                        if (callback != null) {
                            callback.call(CODE_ERROR, "取消选择");
                        }
                    }
                });
    }


    public static interface PictureSelectorCallback {
        void call(int code, String msg, LocalMedia media);
    }

    public void selectImage(Activity activity, String dir, PictureSelectorCallback callback) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .selectionMode(PictureConfig.SINGLE)
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .isCompress(true)// 是否压缩
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        for (LocalMedia media : result) {
                            if (media.getWidth() == 0 || media.getHeight() == 0) {
                                if (PictureMimeType.isHasImage(media.getMimeType())) {
                                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                                    media.setWidth(imageExtraInfo.getWidth());
                                    media.setHeight(imageExtraInfo.getHeight());
                                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(PictureAppMaster.getInstance().getAppContext(), media.getPath());
                                    media.setWidth(videoExtraInfo.getWidth());
                                    media.setHeight(videoExtraInfo.getHeight());
                                }
                            }
                        }

                        String mCoverImagePath = "";
                        if (result.get(0).isCompressed()) {
                            mCoverImagePath = result.get(0).getCompressPath();
                        } else {
                            mCoverImagePath = result.get(0).getRealPath();
                        }
                        String name = FileUtils.getFileName(mCoverImagePath);
                        upload(dir+name, mCoverImagePath, (code, msg) -> {
                            if (callback != null) {
                                if (code == CODE_SUCCESS) {
                                    result.get(0).setCompressPath(msg);
                                    callback.call(code, msg, result.get(0));
                                } else {
                                    callback.call(code, msg, null);
                                }
                            }
                        });
                    }

                    @Override
                    public void onCancel() {
                        if (callback != null) {
                            callback.call(ICloundOS.CODE_ERROR, "取消选择", null);
                        }
                    }
                });
    }

    public void selectVideo(Activity activity, String dir, PictureSelectorCallback callback) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofVideo())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .maxVideoSelectNum(9)
                .filterMaxFileSize(1048575)
                .isCompress(true)// 是否压缩
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        for (LocalMedia media : result) {
                            if (media.getWidth() == 0 || media.getHeight() == 0) {
                                if (PictureMimeType.isHasImage(media.getMimeType())) {
                                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                                    media.setWidth(imageExtraInfo.getWidth());
                                    media.setHeight(imageExtraInfo.getHeight());
                                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(PictureAppMaster.getInstance().getAppContext(), media.getPath());
                                    media.setWidth(videoExtraInfo.getWidth());
                                    media.setHeight(videoExtraInfo.getHeight());
                                }
                            }
                        }
                        String mCoverImagePath = "";
                        if (result.get(0).isCompressed()) {
                            mCoverImagePath = result.get(0).getCompressPath();
                        } else {
                            mCoverImagePath = result.get(0).getRealPath();
                        }
                        String name = FileUtils.getFileName(mCoverImagePath);
                        upload(dir+name, mCoverImagePath, (code, msg) -> {
                            if (callback != null) {
                                if (code == CODE_SUCCESS) {
                                    result.get(0).setCompressPath(msg);
                                    callback.call(code, msg, result.get(0));
                                } else {
                                    callback.call(code, msg, null);
                                }
                            }
                        });
                    }

                    @Override
                    public void onCancel() {
                        if (callback != null) {
                            callback.call(ICloundOS.CODE_ERROR, "取消选择", null);
                        }
                    }
                });
    }

    public void selectAll(Activity activity, String dir, PictureSelectorCallback callback) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofAll())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .maxVideoSelectNum(9)
                .selectionMode(PictureConfig.SINGLE)
                .filterMaxFileSize(1048575)
                .isCompress(true)// 是否压缩
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        for (LocalMedia media : result) {
                            if (media.getWidth() == 0 || media.getHeight() == 0) {
                                if (PictureMimeType.isHasImage(media.getMimeType())) {
                                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                                    media.setWidth(imageExtraInfo.getWidth());
                                    media.setHeight(imageExtraInfo.getHeight());
                                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(PictureAppMaster.getInstance().getAppContext(), media.getPath());
                                    media.setWidth(videoExtraInfo.getWidth());
                                    media.setHeight(videoExtraInfo.getHeight());
                                }
                            }
                        }
                        String mCoverImagePath = "";
                        if (result.get(0).isCompressed()) {
                            mCoverImagePath = result.get(0).getCompressPath();
                        } else {
                            mCoverImagePath = result.get(0).getRealPath();
                        }
                        String name = FileUtils.getFileName(mCoverImagePath);
                        upload(dir+name, mCoverImagePath,  (code, msg) -> {
                            if (callback != null) {
                                if (code == CODE_SUCCESS) {
                                    result.get(0).setCompressPath(msg);
                                    callback.call(code, msg, result.get(0));
                                } else {
                                    callback.call(code, msg, null);
                                }
                            }
                        });
                    }

                    @Override
                    public void onCancel() {
                        if (callback != null) {
                            callback.call(ICloundOS.CODE_ERROR, "取消选择", null);
                        }
                    }
                });
    }
}
