package com.mayi.fastdevelop.view.installapk;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mayi.fastdevelop.R;
import com.mayi.fastdevelop.bean.AppConfig;
import com.mayi.fastdevelop.constant.Key;
import com.mayi.fastdevelop.util.ActivitysManager;
import com.mayi.fastdevelop.util.DownLoadUtil;
import com.mayi.fastdevelop.util.PermissionUtil;
import com.mayi.fastdevelop.util.SpUtil;
import com.mayi.fastdevelop.util.ToastUtil;
import com.mayi.fastdevelop.view.dialog.BaseDialog;
import com.mayi.fastdevelop.view.dialog.DialogViewHolder;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;

import java.util.List;

/**
 * APP 升级管理
 */
public class AppUpgradeManager {

    private Context mContext;
    // 进度条
    private ProgressBar mProgressBar;
    // 进度显示
    private TextView mTxtPercent;
    private TextView mTxtTotal;
    private final int INTERVAL = 500;

    public AppUpgradeManager(Context context) {
        this.mContext = context;
    }

    /**
     * 显示更新提示
     */
    public void showUpdateTipDialog(final AppConfig info) {
        if (!info.isNeedUpdate()) {
            return;
        }
        new BaseDialog(mContext, R.layout.dialog_update) {
            @Override
            public void convert(DialogViewHolder holder) {
                holder.setText(R.id.pack_content, info.getUpdateRemark());
                holder.setText(R.id.pack_size, String.format(mContext.getResources().getString(R.string.package_size), info.getFileSize()));
                holder.setOnClick(R.id.txt_sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                        PermissionUtil.requestPermission(new PermissionUtil.PermissionCallback() {
                            @Override
                            public void onSuccess(List<String> data) {
                                showApkProgressDialog();
                                mHandler.post(mRunnable);
                                DownLoadUtil.downLoadAPK(mContext, info.getUpdateUrl());
                            }

                            @Override
                            public void onFail(List<String> data) {
                                ToastUtil.show(mContext, "没有下载权限，无法下载APK");
                            }
                        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                });
                holder.setOnClick(R.id.txt_cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                        //如果是强制更新  点击取消 直接退出app
                        if (info.isForceUpdate()) {
                            ActivitysManager.exitApp(mContext);
                        }
                    }
                });

                holder.setOnClick(R.id.txt_browsers, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(info.getUpdateUrl());
                        intent.setData(content_url);
                        mContext.startActivity(intent);
                    }
                });
            }
        }.fullWidth()
                .setCancelAble(false)
                .setCanceledOnTouchOutside(false)
                .show();
    }

    /**
     * 显示apk下载进度条
     */
    private void showApkProgressDialog() {
        new BaseDialog(mContext, R.layout.dialog_download_apk_progress) {
            @Override
            public void convert(DialogViewHolder holder) {
                mProgressBar = holder.getConvertView().findViewById(R.id.progress_bar);
                mTxtPercent = holder.getConvertView().findViewById(R.id.txt_percent);
                mTxtTotal = holder.getConvertView().findViewById(R.id.txt_total);
                mTxtPercent.setText("0%");
            }
        }.fullWidth()
                .setCancelAble(false)
                .setCanceledOnTouchOutside(false)
                .show();
    }

    private void updateProgress(int percent, int total) {
        int per = 0;
        if (total == 0) {
            per = 0;
        } else {
            per = (int) (percent * 100f / total);
        }
        if (mProgressBar != null) {
            mProgressBar.setProgress(per);
        }
        if (mTxtPercent != null) {
            mTxtPercent.setText(per + "%");
        }
        if (mTxtTotal != null) {
            mTxtTotal.setText(percent + "/" + total);
        }
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                mHandler.postDelayed(this, INTERVAL);
                final int[] arr = DownLoadUtil.getBytesAndStatus(mContext, SpUtil.get(Key.ANT_DOWNLOAD_ID, -1L));
                if (arr[0] == arr[1]) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            BaseDialog.getDialog().dismiss();
                            mHandler.removeCallbacks(mRunnable);
                        }
                    });
                } else {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            updateProgress(arr[0], arr[1]);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });
}
