package com.baoshi.swms;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.StrictMode;

import androidx.appcompat.app.AppCompatActivity;

import com.baoshi.swms.activity.LoginActivity;
import com.baoshi.swms.activity.MenuActivity;
import com.baoshi.swms.permission.PermissionUtil;
import com.baoshi.swms.util.GlobalStorage;
import com.baoshi.swms.util.Hint;
import com.baoshi.swms.util.NetUtil;
import com.google.gson.Gson;
import com.kongzue.dialogx.DialogX;
import com.kongzue.dialogx.style.MIUIStyle;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

import constant.UiType;
import model.UiConfig;
import model.UpdateConfig;
import update.UpdateAppUtils;

/**
 * 程序启动入口
 *
 * @author Zhendong Zhou
 * @date   2021/12/3 15:52
 */
public class MainActivity extends AppCompatActivity {

    private final String APK_URL = "https://was.baoshi56.com/app/apk.cnf";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DialogX.globalStyle = new MIUIStyle();
        //权限获申请
        permissionApply();

        //检查更新
        if (!checkUpdate()){
            //启动并检查登录状态
            startAndCheckLogin();
        }
    }

    /**
     * 发生错误或者服务器问题都跳过此次更新
     * */
    private boolean checkUpdate() {
        if (!NetUtil.isNetworkConnected(this)){
            Hint.toastShort(this,"您当前无网络!",Hint.COMMON);
            return false;
        }

        String conf = readCnf();
        if (conf==null){
            return false;
        }
        try {
            PackageInfo packInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            Gson gson = new Gson();
            Map<String,String> map = gson.fromJson(conf, Map.class);
            if (packInfo.versionName.equals(map.get("version"))){
                return false;
            }
            executeUpdate(map.get("url"),map.get("title"),map.get("content"));
            return true;
        }catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    private void executeUpdate(String url, String title, String content) {
        UpdateAppUtils.init(this);

        UpdateConfig updateConfig = new UpdateConfig();
        updateConfig.setNeedCheckMd5(false); //目前过不了MD5签名校验，所以先FALSE
        updateConfig.setForce(true);
        updateConfig.setCheckWifi(true);
        updateConfig.setNotifyImgRes(R.drawable.ic_update_logo);

        UiConfig uiConfig = new UiConfig();
        uiConfig.setUiType(UiType.PLENTIFUL);
        UpdateAppUtils
                .getInstance()
                .apkUrl(url)
                .updateTitle(title)
                .updateContent(content)
                .uiConfig(uiConfig)
                .updateConfig(updateConfig)
                .update();
    }

    private void startAndCheckLogin() {
        String token = GlobalStorage.getGlobalStorage().get("token");
        //判断是否已登录
        Intent intent = new Intent(this, token==null ?
                LoginActivity.class : MenuActivity.class);
        //去往登录页时不进入返回栈
        if (token==null)intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);//登录界面不进入返回栈
        startActivity(intent);
    }

    private void permissionApply(){
        //获取存储
        if (!PermissionUtil.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            PermissionUtil.needPermission(this, 89, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }

    //MAIN无内容，离开即从栈内销毁，无需返回此处
    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }

    public String readCnf() {
        try {
            StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            URL url = new URL(APK_URL);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder str = new StringBuilder();
            String s;
            while ((s = in.readLine()) != null) {
                str.append(s);
            }
            in.close();
            return str.toString();
        } catch (Exception e) {
            return null;
        }
    }
}