package com.phlx.anchorcollect.ui.login;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.manager.DownloadManager;
import com.azhon.appupdate.utils.ApkUtil;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.VMFactory;
import com.phlx.anchorcollect.databinding.ActivityLoginBinding;
import com.phlx.anchorcollect.net.RetrofitClient;
import com.phlx.anchorcollect.rfid.ModuleManager;
import com.phlx.anchorcollect.ui.base.BaseActivity;

import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.BR;

public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginVM> {

    private   String downloadUrl ;

    private String path ;

    private int loginType;//登录后是否跳转，0跳转main 1不跳转

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_login;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initParam() {
        super.initParam();

        loginType = getIntent().getIntExtra("loginType", 0);
    }

    @Override
    public LoginVM initViewModel() {
        VMFactory factory = VMFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(LoginVM.class);
    }

    @Override
    public void initData() {
        super.initData();

        viewModel.loginType = loginType;

        downloadUrl = "http://"
                + SPUtils.getInstance().getString(Configs.SP_APP_IP, RetrofitClient.baseUrl)
                + ":" +
                SPUtils.getInstance().getString(Configs.SP_APP_PORT, RetrofitClient.port)
                + Configs.downloadApk;
        path = Environment.getExternalStorageDirectory().getAbsolutePath();

        viewModel.requestVersion(this);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.pSwitchEvent.observe(this, aBoolean -> {
            if (viewModel.pSwitchEvent.getValue()) {
                binding.ivSwitchPwd.setImageResource(R.mipmap.ic_eye_open);
                binding.etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                binding.ivSwitchPwd.setImageResource(R.mipmap.ic_eye_close);
                binding.etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        });
        viewModel.exitEvent.observe(this, aBoolean -> {
            exitApp();
        });

        viewModel.appUpdateEvent.observe(this,new Observer<Integer>() {
            @Override
            public void onChanged(Integer s) {
                int versionCode = ApkUtil.getVersionCode(LoginActivity.this);
                if (versionCode!=s){
                    appUpdate(s);
                }
            }
        });

        viewModel.dateEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                new MaterialDialog.Builder(LoginActivity.this).cancelable(false).canceledOnTouchOutside(false).title("系统提示").content("日期错误，请联网自动获取日期").positiveText("退出").onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            ModuleManager.destroyLibSO();
                            finish();
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    }
                }).show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        exitApp();
    }

    private void exitApp() {
        new MaterialDialog.Builder(this).title("系统提示").content("是否退出程序?").positiveText("确定").negativeText("取消").onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    ModuleManager.destroyLibSO();
                    finish();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        }).show();
    }


    private void appUpdate(int versionCode) {
        UpdateConfiguration configuration = new UpdateConfiguration()
                .setEnableLog(true)
                .setJumpInstallPage(true)
                //设置按钮的文字颜色
                .setDialogButtonTextColor(Color.WHITE)
                //设置是否显示通知栏进度
                .setShowNotification(true)
                //设置是否提示后台下载toast
                .setShowBgdToast(false)
                //设置强制更新
                .setForcedUpgrade(true);
        DownloadManager manager = DownloadManager.getInstance(this);
        manager.setApkName("AnchorCollect.apk")
                .setApkUrl(downloadUrl)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowNewerToast(true)
                .setConfiguration(configuration)
                .setApkVersionCode(versionCode)
                .setApkVersionName(ApkUtil.getVersionName(LoginActivity.this))
                .download();
    }

}
