package com.dahe.mylibrary.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.allenliu.versionchecklib.core.http.HttpParams;
import com.allenliu.versionchecklib.core.http.HttpRequestMethod;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.RequestVersionBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.dahe.mylibrary.R;
import com.dahe.mylibrary.bean.VersionBean;
import com.dahe.mylibrary.dialog.VersionDialog;
import com.dahe.mylibrary.net.CommonResponseBean;
import com.dahe.mylibrary.net.JsonUtils;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

public class VersionUtils {


    private static class SingletonHolder {
        private static final VersionUtils INSTANCE = new VersionUtils();
    }

    private VersionUtils() {
    }

    public static final VersionUtils getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void checkVersion(Context ctx, String api,boolean isShow) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("appType", "0");

        DownloadBuilder request = AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestMethod(HttpRequestMethod.GET)
                .setRequestUrl(api)
                .setRequestParams(httpParams)
                .request(new RequestVersionListener() {
                    @Nullable
                    @org.jetbrains.annotations.Nullable
                    @Override
                    public UIData onRequestVersionSuccess(DownloadBuilder downloadBuilder, String result) {
                        try {
                            if (StringUtils.isEmpty(result))
                                return null;
                            Type type = new TypeToken<CommonResponseBean<VersionBean>>() {
                            }.getType();
                            CommonResponseBean<VersionBean> o = JsonUtils.getInstance().fromJson(result, type);
                            VersionBean.ParamsDao data = o.getData().getData();
                            if ("1".equals(data.getUpdateType())) {
                                downloadBuilder.setForceRedownload(true);
                            }else{
                                downloadBuilder.setForceRedownload(false);
                            }
                            if (AppUtils.getAppVersionCode() < data.getVersion()) {
                                UIData uiData = UIData.create();
                                uiData.setTitle(data.getVersionName());
                                uiData.setDownloadUrl(data.getApkUrl());
                                uiData.setContent(data.getIntroduce());
                                return uiData;
                            }
                            if (isShow){
                                ToastUtils.showToast(ctx,"当前已是最新版本啊!");
                            }
                            return null;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                });

        request.setCustomVersionDialogListener(createCustomDialogTwo(request));
        request.setCustomDownloadingDialogListener(createCustomDownloadingDialog(ctx)).executeMission(ctx);
    }

    private CustomVersionDialogListener createCustomDialogTwo(DownloadBuilder request) {
        return (context, versionBundle) -> {
            VersionDialog baseDialog = new VersionDialog(context, R.style.BaseDialog, R.layout.custom_dialog_two_layout2);
            TextView textView = baseDialog.findViewById(R.id.tv_msg);
            TextView tvVersion = baseDialog.findViewById(R.id.tvVersion);
            tvVersion.setText(request.getVersionBundle().getTitle()+"  版本更新");
            textView.setMovementMethod(ScrollingMovementMethod.getInstance());
            RequestVersionBuilder requestVersionBuilder = request.getRequestVersionBuilder();
//            TextView tvTitle = baseDialog.findViewById(R.id.tv_title);
            baseDialog.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean forceRedownload = request.isForceRedownload();
                    if (forceRedownload){
                        ToastUtils.showToast(context,"请更新版本");
                    }else{
                        baseDialog.cancel();
                        baseDialog.dismiss();
                        AllenVersionChecker.getInstance().cancelAllMission();
                    }

                }
            });
//            textView.setText(versionBundle.getContent());
            textView.setText(versionBundle.getContent());
            baseDialog.setCanceledOnTouchOutside(request.isForceRedownload()?false:true);
            baseDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (KeyEvent.KEYCODE_BACK==event.getKeyCode()&&request.isForceRedownload()){
                        ToastUtils.showToast(context,"请更新版本");
                        return true;
                    }
                    return false;
                }
            });
            baseDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {

                }
            });
            return baseDialog;
        };
    }


    /**
     * 自定义下载中对话框，下载中会连续回调此方法 updateUI
     * 务必用库传回来的context 实例化你的dialog
     *
     * @param ctx
     * @return
     */
    private CustomDownloadingDialogListener createCustomDownloadingDialog(Context ctx) {
        return new CustomDownloadingDialogListener() {
            @Override
            public Dialog getCustomDownloadingDialog(Context context, int progress, UIData versionBundle) {
                VersionDialog baseDialog = new VersionDialog(context, R.style.BaseDialog, R.layout.dialog_download_layout);
                return baseDialog;
            }

            @Override
            public void updateUI(Dialog dialog, int progress, UIData versionBundle) {
                TextView tvProgress = dialog.findViewById(R.id.tv_progress);
                ProgressBar progressBar = dialog.findViewById(R.id.pb);
                progressBar.setProgress(progress);
                tvProgress.setText(ctx.getString(R.string.versionchecklib_progress, progress));
            }
        };
    }

//    private NotificationBuilder createCustomNotification(Context ctx) {
//        return NotificationBuilder.create()
//                .setRingtone(true)
//                .setIcon(R.mipmap.)
//                .setTicker("custom_ticker")
//                .setContentTitle("custom title")
//                .setContentText(ctx.getString(R.string.custom_content_text));
//    }
}
