package com.cooleshow.base.utils.helper;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Base64;
import android.view.KeyEvent;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.cooleshow.base.R;
import com.cooleshow.base.bean.UpdateAppBean;
import com.cooleshow.base.common.AppManager;
import com.cooleshow.base.data.api.AppVersionApi;
import com.cooleshow.base.data.net.BaseResponse;
import com.cooleshow.base.data.net.RetrofitClientNoToken;
import com.cooleshow.base.data.net.RetrofitFactory;
import com.cooleshow.base.utils.AppUtils;
import com.cooleshow.base.utils.EncodeUtils;
import com.cooleshow.base.utils.Utils;
import com.jaygoo.widget.RangeSeekBar;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * Author by pq, Date on 2022/7/14.
 */
public class UpdateAppHelper {
    private static volatile UpdateAppHelper mHelper;

    private UpdateAppHelper() {

    }

    public static UpdateAppHelper getInstance() {
        if (mHelper == null) {
            synchronized (UpdateAppHelper.class) {
                if (mHelper == null) {
                    mHelper = new UpdateAppHelper();
                }
            }
        }
        return mHelper;
    }

    public void checkUpdate(Activity activity, String platform) {
        queryByPlatform(activity, platform);
    }


    private void queryByPlatform(Activity activity, String platform) {
        Observable<BaseResponse<UpdateAppBean>> observable = RetrofitFactory.Companion.getInstance().create(AppVersionApi.class).queryByPlatform(platform);
        observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<UpdateAppBean>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResponse<UpdateAppBean> updateAppBeanBaseResponse) {
                        if (updateAppBeanBaseResponse != null) {
                            handleResult(activity, updateAppBeanBaseResponse.getData());
                        }
                    }

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

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void handleResult(Activity activity, UpdateAppBean data) {
        if (data == null) {
            return;
        }
        if (!TextUtils.isEmpty(AppUtils.getAppVersionName())
                && !TextUtils.isEmpty(data.getVersion())
                && !TextUtils.isEmpty(data.getDownloadUrl()) && ifCanUpdate(data.getVersion())) {
            DownloadBuilder builder = AllenVersionChecker
                    .getInstance()
                    .downloadOnly(UIData.create().setDownloadUrl(EncodeUtils.urlDecode(data.getDownloadUrl()))
                            .setTitle("发现新版本：" + data.getVersion())
                            .setContent(data.getDescription()));
            builder.setCustomVersionDialogListener((context, versionBundle) -> {
                Dialog baseDialog;
                if (data.isIsForceUpdate()) {
                    baseDialog = new Dialog(context, R.style.BaseDialog);
                    baseDialog.setContentView(R.layout.custom_dialog_two_layout);
                    baseDialog.setCancelable(false);
                    baseDialog.setCanceledOnTouchOutside(false);
                } else {
                    baseDialog = new Dialog(context, R.style.BaseDialog);
                    baseDialog.setContentView(R.layout.custom_dialog_one_layout);
                }
                TextView tvTitle = baseDialog.findViewById(R.id.tv_title);
                TextView tvContent = baseDialog.findViewById(R.id.tv_content);
                tvTitle.setText("V" + data.getVersion() + "新版本抢先体验");
                tvContent.setText(versionBundle.getContent());
                baseDialog.setOnKeyListener((dialog, keyCode, event) -> {
                    if (keyCode == KeyEvent.KEYCODE_BACK
                            && event.getAction() == KeyEvent.ACTION_UP) {
                        return true;
                    }
                    return false;
                });
                return baseDialog;
            });
            builder.setCustomDownloadingDialogListener(new CustomDownloadingDialogListener() {
                @Override
                public Dialog getCustomDownloadingDialog(Context context, int progress, UIData versionBundle) {
                    Dialog baseDialog = new Dialog(context, R.style.BaseDialog);
                    baseDialog.setCancelable(false);
                    baseDialog.setCanceledOnTouchOutside(false);
                    baseDialog.setContentView(R.layout.custom_download_layout);
                    RangeSeekBar progressBar = baseDialog.findViewById(R.id.seek_bar);
                    progressBar.setEnabled(false);
                    progressBar.setClickable(false);
                    progressBar.setFocusable(false);
                    baseDialog.setOnKeyListener((dialog, keyCode, event) -> {
                        if (keyCode == KeyEvent.KEYCODE_BACK
                                && event.getAction() == KeyEvent.ACTION_UP) {
                            return true;
                        }
                        return false;
                    });
                    return baseDialog;
                }

                //下载中会不断回调updateUI方法
                @Override
                public void updateUI(Dialog dialog, int progress, UIData versionBundle) {
                    RangeSeekBar progressBar = dialog.findViewById(R.id.seek_bar);
                    progressBar.setProgress(progress);
                    progressBar.setIndicatorText(Integer.valueOf(progress) + "%");
                }
            });

            builder.setCustomDownloadFailedListener((context, versionBundle) -> {
                Dialog baseDialog;
                if (data.isIsForceUpdate()) {
                    baseDialog = new Dialog(context, R.style.BaseDialog);
                    baseDialog.setContentView(R.layout.custom_download_failed_two_dialog);
                    baseDialog.setCancelable(false);
                    baseDialog.setCanceledOnTouchOutside(false);
                } else {
                    baseDialog = new Dialog(context, R.style.BaseDialog);
                    baseDialog.setContentView(R.layout.custom_download_failed_dialog);
                }
                baseDialog.setOnKeyListener((dialog, keyCode, event) -> {
                    if (keyCode == KeyEvent.KEYCODE_BACK
                            && event.getAction() == KeyEvent.ACTION_UP) {
                        return true;
                    }
                    return false;
                });
                return baseDialog;
            });
            builder.setForceRedownload(true); //在本地有安装包时，是否重新下载默认alse
            if (data.isIsForceUpdate()) {
                builder.setForceUpdateListener(new ForceUpdateListener() {
                    @Override
                    public void onShouldForceUpdate() {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AppManager.Companion.getInstance().finishAllActivity();
                            }
                        }, 500);
                    }
                });
            }
            builder.executeMission(activity);
        }
    }

    public static boolean ifCanUpdate(String onlineVersion) {
        String localVersion = AppUtils.getAppVersionName();
        if (TextUtils.isEmpty(onlineVersion)) {
            return false;
        } else {
            if (localVersion.compareTo(onlineVersion) < 0) {  //相等返回0，前者大返回值大于0，前者小返回值小于0
                return true;
            } else {
                return false;
            }
        }
    }
}
