package com.rv.version.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.rv.version.VersionUpdateDialog;
import com.rv.version.bean.UpdateBean;

import pub.devrel.easypermissions.AppSettingsDialog;

public class UpdateAppUtils {

    private final String TAG = "UpdateAppUtils";

    public static final int CHECK_BY_VERSION_NAME = 1001;
    public static final int CHECK_BY_VERSION_CODE = 1002;
    public static final int DOWNLOAD_BY_APP = 1003;
    public static final int DOWNLOAD_BY_BROWSER = 1004;

    private Activity activity;

    public static boolean showNotification = true;

    private boolean isShowToast = false;

    // 将所有的 属性 放入model
    private UpdateBean updateBean = new UpdateBean();

    private UpdateAppUtils(Activity activity) {
        this.activity = activity;
        getAPPLocalVersion(activity);
    }

    public static UpdateAppUtils from(Activity activity) {
        return new UpdateAppUtils(activity);
    }

    public UpdateAppUtils checkBy(int checkBy) {
        updateBean.setCheckBy(checkBy);
        return this;
    }

    public UpdateAppUtils apkPath(String apkPath) {
        updateBean.setApkPath(apkPath);
        return this;
    }

    public UpdateAppUtils apkSize(String packageSize) {
        updateBean.setPackageSize(packageSize);
        return this;
    }

    public UpdateAppUtils downloadBy(int downloadBy) {
        updateBean.setDownloadBy(downloadBy);
        return this;
    }

    public UpdateAppUtils showNotification(boolean showNotification) {
        updateBean.setShowNotification(showNotification);
        this.showNotification = showNotification;
        return this;
    }

    public UpdateAppUtils updateInfo(String updateInfo) {
        updateBean.setUpdateInfo(updateInfo);
        return this;
    }


    public UpdateAppUtils serverVersionCode(int serverVersionCode) {
        updateBean.setServerVersionCode(serverVersionCode);
        return this;
    }

    public UpdateAppUtils serverVersionName(String serverVersionName) {
        updateBean.setServerVersionName(serverVersionName);
        return this;
    }

    public UpdateAppUtils isForce(boolean isForce) {
        updateBean.setForce(isForce);
        return this;
    }

    public UpdateAppUtils isShowToast(boolean isShowToast) {
        this.isShowToast = isShowToast;
        return this;
    }


    /**
     * 获取apk的版本号 currentVersionCode
     */
    private void getAPPLocalVersion(Context ctx) {
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);

            updateBean.setLocalVersionCode(info.versionCode);
            updateBean.setLocalVersionName(info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查更新
     */
    public void update() {

        switch (updateBean.getCheckBy()) {
            case CHECK_BY_VERSION_CODE:
                if (updateBean.getServerVersionCode() > updateBean.getLocalVersionCode()) {
                    toUpdate();
                } else {
                    if (isShowToast)
                        Toast.makeText(activity, "当前版本是最新版本", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "当前版本是最新版本" + updateBean.getServerVersionCode() + "/" + updateBean.getServerVersionName());
                }
                break;

            case CHECK_BY_VERSION_NAME:
                if (!updateBean.getServerVersionName().equals(updateBean.getLocalVersionName())) {
                    toUpdate();
                } else {
                    if (isShowToast)
                        Toast.makeText(activity, "当前版本是最新版本", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "当前版本是最新版本" + updateBean.getServerVersionCode() + "/" + updateBean.getServerVersionName());
                }
                break;
        }
    }

    public static String getAppVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 更新
     */

    private VersionUpdateDialog.Builder builder;

    private void toUpdate() {
        builder = new VersionUpdateDialog.Builder(activity, listener).setData(updateBean).show();
    }

    private VersionUpdateDialog.Builder.DownloadListener listener = () -> preDownLoad();

    /**
     * 预备下载 进行 6.0权限检查
     */
    @SuppressLint("CheckResult")
    private void preDownLoad() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(activity).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            ).subscribe(aBoolean -> {
                if (aBoolean == true) {
                    download();
                } else {
                    new AppSettingsDialog.Builder(activity).
                            setTitle("需要存储权限")
                            .setRationale("如果没有此权限，滴房车无法正常更新")
                            .build().show();
                }
            });
        } else {
            download();
        }
    }

    public void download() {
        Toast.makeText(activity.getApplicationContext(), "下载中...", Toast.LENGTH_SHORT).show();
        DownloadAppUtils.download(activity, updateBean.getApkPath(), updateBean.getServerVersionName());
        if (builder != null) {
            builder.showDownDialog();
        }
    }
}