package com.mogo.cloud.tanlu.core;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mogo.cloud.network.BaseData;
import com.mogo.cloud.passport.MoGoAiCloudClient;
import com.mogo.cloud.tanlu.api.ITanluUploadCallback;
import com.mogo.cloud.tanlu.bean.InformationBody;
import com.mogo.cloud.tanlu.bean.UploadInfo;
import com.mogo.cloud.tanlu.bean.UploadResult;
import com.mogo.cloud.tanlu.constant.HttpConstant;
import com.zhidao.cosupload.DbPriorityConfig;
import com.zhidao.cosupload.callback.CosStatusCallback;
import com.zhidao.cosupload.callback.CosStatusCallbackManager;
import com.zhidao.cosupload.manager.CosUploadManagerImpl;

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

import static com.mogo.cloud.tanlu.utils.FileUtilKt.deletePicFile;
import static com.mogo.cloud.tanlu.utils.FileUtilKt.getVideoPicPath;
import static com.mogo.cloud.tanlu.utils.FileUtilKt.getVideoThumbnail;
import static com.mogo.cloud.tanlu.utils.TanluUtils.isVideo;

/**
 * @author lixiaopeng
 * @description cos上传服务
 * @since 2021/1/21
 */
public class CosUpload implements CosStatusCallback {
    private static CosUpload sInstance;
    private Context mContext;
    private String mPicEventId;
    private ITanluUploadCallback mCallback;
    private UploadInfo mUploadInfo;
    private String mCosVideoUrl;
    private String mCosPicUrl;
    private final List<String> filePath = new ArrayList<>();
    private String videoCoverImage;

    private CosUpload(Context context) {
        mContext = context;
    }

    public static CosUpload getInstance(Context context) {
        if (sInstance == null) {
            synchronized (CosUpload.class) {
                sInstance = new CosUpload(context);
            }
        }

        return sInstance;
    }

    public void init () {
        CosStatusCallbackManager.getInstance().register(this);
        mPicEventId =
                CosUploadManagerImpl.getInstance(mContext.getApplicationContext()).getEventId();
        UploadManager.getInstance(mContext.getApplicationContext()).init();
    }

    public void uploadInfo(UploadInfo info, ITanluUploadCallback callback) {
        mCallback = callback;
        mUploadInfo = info;

        if (!TextUtils.isEmpty(info.getFilePath())) { //不传路径
            if (isVideo(info.getFilePath())) {
                videoCoverImage = getVideoPicPath();
                boolean isSuccess = getVideoThumbnail(info.getFilePath(), videoCoverImage);
                if (MoGoAiCloudClient.getInstance().getAiCloudClientConfig().isShowDebugLog()) {
                    Log.d(HttpConstant.TAG, "isSuccess = " + isSuccess + "--videoCoverImage = " + videoCoverImage);
                }
                filePath.add(info.getFilePath());
                filePath.add(videoCoverImage);
            } else {
                videoCoverImage = null;
                filePath.add(info.getFilePath());
            }
            if (MoGoAiCloudClient.getInstance().getAiCloudClientConfig().isShowDebugLog()) {
                Log.d(HttpConstant.TAG, "filePath.size() = " + filePath.size());
            }
            CosUploadManagerImpl.getInstance(mContext.getApplicationContext())
                    .upload(filePath, mPicEventId, DbPriorityConfig.PRIORITY_HIGH);
        } else {
            //直接上报
            sendInformation();
        }
    }

    @Override
    public void onStartUpload(String eventId, String localPath) {

    }

    @Override
    public void uploadCosCompleted(String cosPath, String eventId, String downloadUrl, String localPath) {
        if (MoGoAiCloudClient.getInstance().getAiCloudClientConfig().isShowDebugLog()) {
            Log.d(HttpConstant.TAG, "uploadCosCompleted ----> cosPath =" + cosPath + "--eventId =" + eventId);
            Log.d(HttpConstant.TAG, "uploadCosCompleted ----> downloadUrl =" + downloadUrl + "--localPath =" + localPath);
        }
        if (filePath.size() == 2) {
            if (isVideo(localPath)) { //如果是视频 localPath
                mCosVideoUrl = downloadUrl;
            } else {
                mCosPicUrl = downloadUrl;
            }
            if (MoGoAiCloudClient.getInstance().getAiCloudClientConfig().isShowDebugLog()) {
                Log.d(HttpConstant.TAG, "mCosVideoUrl = " + mCosVideoUrl + " >>>mCosPicUrl = " + mCosPicUrl);
            }
            if (mCosPicUrl != null && mCosVideoUrl != null) {
                sendInformation();
            }
        } else {
            mCosPicUrl = downloadUrl;
            sendInformation();
        }
    }

    @Override
    public void uploadCosFailed(String cosPath, String eventId, String localPath) {
        if (MoGoAiCloudClient.getInstance().getAiCloudClientConfig().isShowDebugLog()) {
            Log.e(HttpConstant.TAG, "uploadCosFailed ----> cosPath = " + cosPath + "--eventId =" + eventId +  "--localPath =" + localPath);
        }
        sendInformation();
    }

    @Override
    public void onProgress(String localPath, float progress) {

    }

    private void sendInformation() {
        //清理数据
        if (filePath != null) {
            filePath.clear();
        }

        //删除本地生成的图片封面
        if (videoCoverImage != null) {
            deletePicFile(videoCoverImage);
        }

        UploadManager.getInstance(mContext.getApplicationContext()).loadUpload(getInformation(), new ITanluUploadCallback() {
            @Override
            public void onSuccess(BaseData<UploadResult> result) {
                if (result != null && result.getResult() != null) {
                    if (MoGoAiCloudClient.getInstance().getAiCloudClientConfig().isShowDebugLog()) {
                        Log.d(HttpConstant.TAG, "uploadRoadInfo result.id = " + result.getResult().id);
                    }
                }
                mCallback.onSuccess(result);
            }

            @Override
            public void onFailure(int code) {
                mCallback.onFailure(code);
            }

            @Override
            public void onError(Throwable e) {
                mCallback.onError(e);
            }
        });
    }

    private InformationBody getInformation() {
        InformationBody informationBody = new InformationBody();
        JsonArray jsonArray = new JsonArray();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("thumbnail", mCosPicUrl);
        jsonObject.addProperty("url", mCosVideoUrl);
        jsonArray.add(jsonObject);

        informationBody.setData(jsonArray.toString());
        informationBody.setAddr(mUploadInfo.getAddr());
        informationBody.setAreaCode(mUploadInfo.getAreaCode());
        informationBody.setAreaName(mUploadInfo.getAreaName());
        informationBody.setCityCode(mUploadInfo.getCityCode());
        informationBody.setCityName(mUploadInfo.getCityName());
        informationBody.setDirection(mUploadInfo.getDirection());
        informationBody.setFromType(mUploadInfo.getFromType());
        informationBody.setGenerateTime(mUploadInfo.getGenerateTime());
        informationBody.setInfoTimeout(mUploadInfo.getInfoTimeout());
        informationBody.setInfoType(mUploadInfo.getInfoType());
        informationBody.setLat(mUploadInfo.getLatitude());
        informationBody.setLon(mUploadInfo.getLongitude());
        informationBody.setMainInfoId(mUploadInfo.getMainInfoId());
        informationBody.setPoiType(mUploadInfo.getPoiType());
        informationBody.setProvinceName(mUploadInfo.getProvinceName());
        informationBody.setStreet(mUploadInfo.getStreet());
        informationBody.setSn(mUploadInfo.getSn());
        informationBody.setUid(mUploadInfo.getUid());
        informationBody.setShare(mUploadInfo.isShare());
        informationBody.setType(mUploadInfo.getType());
        informationBody.setSpeed(mUploadInfo.getSpeed());

        return informationBody;
    }

}
