package com.phlx.wool.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.wool.BR;
import com.phlx.wool.Configs;
import com.phlx.wool.R;
import com.phlx.wool.data.VMFactory;
import com.phlx.wool.databinding.ActivityLoginBinding;
import com.phlx.wool.net.RetrofitClient;
import com.phlx.wool.rfid.ModuleManager;
import com.phlx.wool.ui.base.BaseActivity;

import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * <pre>
 *     author : lei
 *     e-mail : 18600395998@163.com
 *     time   : 2020/04/21
 *     desc   : 登录页
 *     version: 1.0
 * </pre>
 */
public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginVM> {

  private   String downloadUrl ;
   private String path ;

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

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

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

    @Override
    public void initData() {
        super.initData();
        setSupportActionBar(binding.include.toolbar);
        viewModel.initToolbar();
        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() {
        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);
                }
            }
        });
    }


    @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("WoolManager.apk")
                .setApkUrl(downloadUrl)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowNewerToast(true)
                .setConfiguration(configuration)
                .setApkVersionCode(versionCode)
                .setApkVersionName(ApkUtil.getVersionName(LoginActivity.this))
                .download();
    }



}
