package com.duben.microtribe.mvp.presenters;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;

import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.duben.microtribe.MintsApplication;
import com.duben.microtribe.R;
import com.duben.microtribe.common.AppConfig;
import com.duben.microtribe.common.Constant;
import com.duben.microtribe.mvp.model.BaseResponse;
import com.duben.microtribe.mvp.model.Version;
import com.duben.microtribe.net.LoanService;
import com.duben.microtribe.ui.service.UpdateService;
import com.duben.microtribe.utils.ToastUtil;
import com.duben.library.net.neterror.BaseSubscriber;
import com.duben.library.net.neterror.Throwable;
import com.duben.library.utils.CommonUtils;
import com.duben.library.utils.ConstantUtil;

import java.util.HashMap;
import java.util.LinkedList;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

/**
 * 描述：版本更新
 * 作者：孟崔广
 * 时间：2017/10/10 10:51
 * 邮箱：mengcuiguang@cashbang.cn
 */
public class VersionUpdatePresenter {

    private MintsApplication loanApplication;
    private LoanService loanService;
    private AlertDialog dialogDetails;
    private String version;
    private Activity activity;

    ProgressBar pbDuUpdating;
    Button btnDuUpdate;
    private Subscription subscription;


    public void updateVersion(Activity activity) {
        if (activity == null)
            return;

        this.activity = activity;
        loanApplication = (MintsApplication) activity.getApplication();

        version = ConstantUtil.getVersionName(loanApplication);

        if (dialogDetails == null || !dialogDetails.isShowing()) {

            loanApplication = (MintsApplication) activity.getApplication();
            loanService = loanApplication.getLoanService();

            HashMap<String, Object> vo = new HashMap<>();
            vo.put("platform", "android");
            vo.put("version", version);
            subscription = loanService.checkUpgrade(vo)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(loanApplication.defaultSubscribeScheduler())
                    .subscribe(new BaseSubscriber<BaseResponse<Version>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(BaseResponse<Version> baseResponse) {
                            //这个activity是不是可见状态
                            if (!activity.isFinishing()) {
                                int code = baseResponse.getStatus();
                                switch (code) {
                                    case 200://成功
                                        Version content = baseResponse.getData();
                                        if (content != null) {
                                            getUpdateVersion(content);
                                        }
                                        break;
                                }
                            }
                        }
                    });
        }
    }

    private void getUpdateVersion(Version content) {
        LinkedList<Version.UpgradesBean> upgrades = content.getUpgrades();

        //查看弹出框是否已经弹出
        if (AppConfig.app_updateing) {
            return;
        }

        Version.UpgradesBean upgradesBean;
        if (upgrades == null || upgrades.isEmpty()) {
            return;
        } else {
            upgradesBean = upgrades.getFirst();
        }

        boolean forceUpgrade = content.isForceUpgrade();

//        new RxPermissions(activity)
//                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                .subscribe(granted -> {
//                    urlUpdateApp(upgradesBean, forceUpgrade, granted);
//                });
        urlUpdateApp(upgradesBean, forceUpgrade, true);

        //标记已弹出更新框
        AppConfig.app_updateing = true;

    }

    /**
     * 通过url更新app
     *
     * @param bean         更新对象
     * @param forceUpgrade 是否强制更新
     * @param granted      是否正常获取sd卡写入权限
     */
    private void urlUpdateApp(Version.UpgradesBean bean, boolean forceUpgrade, boolean granted) {
        if (activity == null)
            return;

        String appFileUrl;
        String updatemsg = bean.getUpdatemsg();
        if (TextUtils.isEmpty(updatemsg)) {
            updatemsg = loanApplication.getString(R.string.update_text4);
        } else {
            updatemsg = updatemsg.replace("\\n", "\n");
        }

        if (granted) {
            appFileUrl = bean.getUrl();
        } else {
            appFileUrl = "https://mints-gs.oss-cn-beijing.aliyuncs.com/pkg/mints.apk";
        }

        View v_details = View.inflate(activity, R.layout.view_dialog_update, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.notice_dialog);
        dialogDetails = builder.create();
        dialogDetails.setView(v_details);

        pbDuUpdating = (ProgressBar) v_details.findViewById(R.id.pb_du_updating);
        TextView tvDuDialogdetails = (TextView) v_details.findViewById(R.id.tv_du_dialogdetails);
        btnDuUpdate = (Button) v_details.findViewById(R.id.btn_du_update);
        ImageView ivDilogKnow = (ImageView) v_details.findViewById(R.id.iv_dilog_know);

        tvDuDialogdetails.setMovementMethod(new ScrollingMovementMethod());

        tvDuDialogdetails.setText(updatemsg);

        if (!forceUpgrade) {
            // 非强升
            btnDuUpdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialogDetails != null && dialogDetails.isShowing()) {
                        dialogDetails.dismiss();
                        AppConfig.app_updateing = false;
                    }

                    boolean url = CommonUtils.isUrl(appFileUrl);
                    if (url) {
                        updateApp(appFileUrl, granted);
                    }

                }
            });

            ivDilogKnow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dialogDetails != null && dialogDetails.isShowing()) {
                        dialogDetails.dismiss();
                    }
                }
            });

        } else {
            ivDilogKnow.setVisibility(View.GONE);

            btnDuUpdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean url = CommonUtils.isUrl(appFileUrl);
                    if (url) {
                        updateApp(appFileUrl, granted);

                        //如果已经获取到sd卡存储权限则把按钮设置成不可点击
                        if (granted) {
                            btnDuUpdate.setEnabled(false);
                        }

                    }

                }
            });
            dialogDetails.setCanceledOnTouchOutside(false);
            dialogDetails.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        return true;
                    }
                    return false;
                }
            });
        }

        dialogDetails.show();
    }

    /**
     * service 连接通道
     */
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

//            //返回一个MsgService对象  
            UpdateService updateService = ((UpdateService.UpdateBinder) service).getService();
//
//            //注册回调接口来接收下载进度的变化  
            updateService.setUpdateNotification(new UpdateService.UpdateNotification() {
                @Override
                public void updateProgress(int progress) {
                    if (pbDuUpdating != null) {
                        pbDuUpdating.setProgress(progress);
                        if (btnDuUpdate != null && progress == 100) {
                            btnDuUpdate.setEnabled(true);
                        }
                    }
                }

                @Override
                public void finishProgress() {

                }
            });

        }
    };

    /**
     * 更新app
     *
     * @param appFileUrl
     * @param granted
     */
    private void updateApp(String appFileUrl, boolean granted) {

        if (loanApplication == null || activity == null)
            return;

        //判断权限是否已获取
        if (!granted) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(appFileUrl));
            activity.startActivity(intent);
        } else {
            Context applicationContext = loanApplication.getApplicationContext();
            Intent updateIntent = new Intent(applicationContext, UpdateService.class);
            updateIntent.putExtra("path", appFileUrl);
            updateIntent.putExtra("app_name", Constant.MINTS_PKG_NAME);
            updateIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            applicationContext.bindService(updateIntent, conn, Context.BIND_AUTO_CREATE);

            ToastUtil.show(MintsApplication.getContext(), loanApplication.getString(R.string.update_text6));
        }
    }

    public void dispose() {
        loanService = null;
        activity = null;
        loanApplication = null;

        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }

}
