package com.example.bpa.helper;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.capton.colorfulprogressbar.ColorfulProgressbar;
import com.example.bpa.R;
import com.example.bpa.config.ConfigName;

import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/*
 * 检验apk是否有新版本，是否升级
 * @author fengyoufu 20230518
 */
public class UpdateManager {

    /* 上下文 */
    private Context mContext;

    /* 下载包安装路径 */
    private static final String savePath = ConfigName.getInstance().appResRoot+"/Download/";

    private static final int NEW_VERSION = 3;

    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;

    /* 刷新的进度条  */
    private ColorfulProgressbar mProgress;

    /* 新版本apk的远程路径 */
    private String apkUrl ;

    /* 保存下载的apk的名称为 */
    private String saveFileName;

    /* 下载进度 */
    private int progress;

    private boolean interceptFlag = false;

    /*
     * Handler静态化，防止内存泄露
     */
    private static class MHandler extends Handler
    {
        /* 引用外部类 */
        private WeakReference<UpdateManager> updatemanager;

        public MHandler(UpdateManager activity)
        {
            updatemanager = new WeakReference<UpdateManager>(activity);
        }

        /* 处理线程结果 */
        @Override
        public void handleMessage(android.os.Message msg)
        {
            UpdateManager theClass = updatemanager.get();
            switch (msg.what)
            {
                //对比后有新版本
                case NEW_VERSION:
                    JSONObject jsonObject=(JSONObject)msg.obj;
                    theClass.showUpdateDialog(jsonObject);
                    break;
                //正在下载，更新进度条
                case DOWN_UPDATE:
                    theClass.showProgress();
                    break;
                //下载完成，进行安装
                case DOWN_OVER:
                    theClass.installApkNew();
            }
        }
    }

    /* 实例化Handler */
    MHandler mHandler = new MHandler(this);

    //构造函数
    public UpdateManager(Context context) {
        this.mContext = context;
    }

    /*
     * 检查新版本
     */
    public void checkVersion()
    {
        android.util.Log.i("UpdateManager","checkVersion");
        Runnable checkVersionRunnable = new Runnable(){
            @Override
            public void run()
            {
                try
                {
                    //远程请求服务器，获取远程服务器上的apk版本；这里我们直接模拟返回的结果
                    JSONObject data = new JSONObject("{"
                            + "\"status\":1,"
                            + "\"msg\":{"
                            + "\"versionCode\":2,"
                            + "\"versionName\":\"1.1.7\","
                            + "\"versionUrl\":\"http://124.222.238.75/blnc1.apk\","
                            + "\"versionDesc\":\"1，修复商品制作;2，优化商品配方管理;3，增加云版本更新;4，增加针对信息推送功能;\","
                            + "\"versionDate\":\"2023.06.01\","
                            + "\"versionSize\":\"17.4M\"}}");
                    if(data.length()>0)   //有返回数据，则发送消息
                    {
                        int status = data.getInt("status");
                        if(status==1)
                        {
                            JSONObject newVersionInfo = data.getJSONObject("msg");
                            int versionCode = newVersionInfo.getInt("versionCode");
                            String versionName = newVersionInfo.getString("versionName");
                            saveFileName = "hlnc_"+versionName+".apk";
                            apkUrl = newVersionInfo.getString("versionUrl");
                            int versionCodeClient = Utils.getversionCode(mContext);
                            if(versionCode>versionCodeClient)   //服务器版本大于本机版本，则视为有新版本
                            {
                                Message message = mHandler.obtainMessage(NEW_VERSION);
                                message.obj = newVersionInfo;
                                mHandler.sendMessage(message);
                            }else
                            {
                                T.show(mContext,"当前无更新内容！");
                            }
                        }else
                        {
                            T.show(mContext,"当前无更新内容！");
                        }
                    }else
                    {
                        T.show(mContext,"当前无更新内容！");
                    }
                }
                catch(Exception e)
                {
                    android.util.Log.i("UpdateManager",e.toString());
                }
            }
        };
        new Thread(checkVersionRunnable).start();;
    }

    /* 显示进度条
     * 外部类进行封装以便MHandler进行内部调用
     */
    public void showProgress()
    {
        mProgress.setProgress(progress);
        mProgress.setSecondProgress(progress);
    }

    /*
     * 显示版本更新提示框
     */
    private void showUpdateDialog(JSONObject newVersionInfo){
        final AlertDialog alg = new AlertDialog.Builder(mContext).create();
        alg.show();
        Window win = alg.getWindow();
        win.setContentView(R.layout.common_dialog_update);

        //显示新版本内容
        TextView title_update = (TextView)win.findViewById(R.id.title_update);
        TextView title_date = (TextView)win.findViewById(R.id.title_date);
        TextView title_size = (TextView)win.findViewById(R.id.title_size);
        TextView versionDesc = (TextView)win.findViewById(R.id.versionDesc);
        try{
            title_update.setText(newVersionInfo.getString("versionName")+"版本升级提示");
            title_date.setText("发布时间："+newVersionInfo.getString("versionDate"));
            title_size.setText("大小："+newVersionInfo.getString("versionSize"));
            //提示内容按";"进行整合，这里拆分到数组中
            String desc= newVersionInfo.getString("versionDesc").replace(";","\n");
            versionDesc.setText(desc);
            Button positiveButton = (Button)win.findViewById(R.id.PositiveButton);
            Button negativeButton = (Button)win.findViewById(R.id.NegativeButton);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    alg.dismiss();
                    showDownloadDialog();
                }
            });
            negativeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    alg.dismiss();
                }
            });
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /*
     * 显示下载中界面
     */
    private void showDownloadDialog(){
        final AlertDialog alg = new AlertDialog.Builder(mContext).create();
        alg.show();
        Window win = alg.getWindow();
        win.setContentView(R.layout.common_dialog_progress);
        mProgress = (ColorfulProgressbar)win.findViewById(R.id.update_progress);
        mProgress.showPercentText(true);
        mProgress.setAnimation(true);
        Button negativeButton = (Button)win.findViewById(R.id.NegativeButton);
        negativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alg.dismiss();
                interceptFlag = true;   //中止下载
            }
        });
        downloadApk();
    }

    /*
     * 下载apk
     * @param url
     */
    private void downloadApk(){
        Runnable mdownApkRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(apkUrl);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    File file = new File(savePath);
                    if (!file.exists()) //创建目录
                    {
                        file.mkdirs();
                    }
                    File ApkFile = new File(file,saveFileName);
                    FileOutputStream fos = new FileOutputStream(ApkFile);
                    int count = 0;
                    byte buf[] = new byte[1024];

                    do{
                        int numread = is.read(buf);
                        count += numread;
                        progress =(int)(((float)count / length) * 100);
                        //更新进度
                        mHandler.sendEmptyMessage(DOWN_UPDATE);
                        if(numread <= 0){
                            //下载完成通知安装
                            mHandler.sendEmptyMessage(DOWN_OVER);
                            T.show(mContext,"下载完成,正在安装...");
                            break;
                        }
                        fos.write(buf,0,numread);
                    }while(!interceptFlag); //点击取消就停止下载.
                    fos.close();
                    is.close();
                } catch (MalformedURLException e) {
                    android.util.Log.i("MalformedURLException",e.toString());
                } catch(IOException e){
                    android.util.Log.i("IOException",e.toString());
                }

            }
        };
        new Thread(mdownApkRunnable).start();
    }

    /*
     * 安装apk
     * @param url
     */
    private void installApk(){
        try {
            File apkfile = new File(savePath + saveFileName);
            if (!apkfile.exists()) {
                return;
            }
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //com.example.silentinstallation.fileprovider
            Uri uri = Uri.parse("file://" + apkfile.toString());
            i.setDataAndType(uri, "application/vnd.android.package-archive");
            mContext.startActivity(i);
        } catch(Exception e){
            T.show(mContext,"错误信息,正在安装..."+e.getMessage());
        }
    }

    private void installApkNew(){
        try {

            File apkfile = new File(savePath + saveFileName);
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //fileprovider为上述manifest中provider所配置相同
                uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkfile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                uri = Uri.fromFile(apkfile);
            }
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } catch(Exception e){
            T.show(mContext,"错误信息,正在安装..."+e.getMessage());
        }
    }
}