package com.app.duck.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.duck.BuildConfig;
import com.app.duck.R;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;

public class UploadAppDialog extends Dialog implements View.OnClickListener {

    private boolean isForce;
    private String description;
    private String versionName;
    private String title;
    private int versionCode;
    private boolean toast;


    private View choseLayout;
    private View progressLayout;
    private ProgressBar downLoadProgress;
    private TextView rateTv;
    private TextView updateTxtTv;
    private TextView titleTv;
    private int rate;


    public UploadAppDialog(@NonNull Context context, String jsonTxt, boolean toast) {
        super(context, R.style.dialog);

        JSONObject object = JSON.parseObject(jsonTxt);
        isForce = object.getBooleanValue("isForce");//是否强制更新
        description = object.getString("description");//更新描述
        versionName = object.getString("versionName");//版本号
        versionCode = object.getIntValue("versionCode");//版本号
        this.toast = toast;
        title = object.getString("title");//标题
        if (versionCode > AppUtils.getAppVersionCode()) {
            show();
        } else {
            if (toast) {
                ToastUtils.showLong(AppUtils.getAppVersionName() + "[" + AppUtils.getAppVersionCode() + "]" + StringUtils.getString(R.string.uplaod_null_tip));
            }
        }


    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_upload_app);
        View submitBt = findViewById(R.id.submitBt);
        View cancelBt = findViewById(R.id.cancelBt);
        downLoadProgress = findViewById(R.id.downLoadProgress);
        updateTxtTv = findViewById(R.id.updateTxtTv);
        titleTv = findViewById(R.id.titleTv);
        choseLayout = findViewById(R.id.choseLayout);
        progressLayout = findViewById(R.id.progressLayout);
        rateTv = findViewById(R.id.rate);
        TextView versionCodeTv = findViewById(R.id.versionCodeTv);
        updateTxtTv.setText(description);
        titleTv.setText(title);

        submitBt.setOnClickListener(this);
        cancelBt.setOnClickListener(this);

        if (!isForce) {
            cancelBt.setVisibility(View.VISIBLE);
        } else {
            //不可被取消
            setCancelable(false);
            setCanceledOnTouchOutside(false);
        }

        versionCodeTv.setText(versionName);
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.submitBt) {
            choseLayout.setVisibility(View.GONE);
            progressLayout.setVisibility(View.VISIBLE);
            String fileName = AppUtils.getAppName() + ".apk";
            RequestParams params = new RequestParams(BuildConfig.UPDATE_BASE_URL + BuildConfig.UPDATE_APP_NAME);
            File fileUrl = new File(Utils.getApp().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName);
            params.setSaveFilePath(fileUrl.getAbsolutePath());
            params.setAutoRename(true);
            x.http().get(params, new Callback.ProgressCallback<File>() {
                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {

                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {
                    downLoadProgress.setMax((int) total);
                    downLoadProgress.setProgress((int) current);
                    rate = (int) (((float) current / total) * 100);
                    rateTv.setText(rate + "%");
                }


                @Override
                public void onSuccess(File result) {
                    try {
                        rateTv.setText("100%");
                        String command = "chmod " + "777" + " " + result.getAbsolutePath();
                        Runtime runtime = Runtime.getRuntime();
                        runtime.exec(command);
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (Build.VERSION.SDK_INT >= 24) {
                            File file = (new File(result.getAbsolutePath()));
                            Uri apkUri = FileProvider.getUriForFile(getContext(), Utils.getApp().getPackageName() + ".fileprovider", file);
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                        } else {
                            intent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS, result.getName())), "application/vnd.android.package-archive");
                        }
                        getContext().startActivity(intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    rateTv.setText("0%");
                    downLoadProgress.setProgress(0);
                    progressLayout.setVisibility(View.GONE);
                    choseLayout.setVisibility(View.VISIBLE);
                }
            });
        } else if (id == R.id.cancelBt) {
            dismiss();
        }
    }

}
