package com.hjx.miaohongentry.update;

/**
 * Created by l on 2017/7/17.
 */

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ResultReceiver;
import android.util.Log;


import com.hjx.miaohongentry.bean.AppVersion;
import com.hjx.miaohongentry.http.MHGetApiImp;

import java.io.File;

public class UpdateChecker {
    private static final String TAG = "UpdateChecker";
    private Context mContext;
    //检查版本信息的线程
    private Thread mThread;

    private AppVersion mAppVersion;
    //下载apk的对话框
    private ProgressDialog mProgressDialog;

    private File apkFile;


    public UpdateChecker(Context context) {
        mContext = context;
        // instantiate it within the onCreate method
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("正在下载");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

            }
        });
        mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub

            }
        });
    }

    public void checkForUpdates() {

        final Handler handler = new Handler(){
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    mAppVersion = (AppVersion) msg.obj;
                    try{
                        int versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
                        if (mAppVersion.getVersionCode() > versionCode) {
                            if(mAppVersion.isForceUpdate()){
                                showForceUpdateDialog();
                            }else{
                                showUpdateDialog();
                            }
                        } else {
                            //Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
                        }
                    }catch (PackageManager.NameNotFoundException ignored) {
                        //
                    }
                }
            }
        };

        mThread = new Thread() {
            @Override
            public void run() {
                //if (isNetworkAvailable(mContext)) {
                try {
                    MHGetApiImp imp = new MHGetApiImp();
                    String pkgName = mContext.getPackageName();

                    PackageInfo pkg = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
                 //   String appName = pkg.applicationInfo.loadLabel(mContext.getPackageManager()).toString();
                    String appName = "练汉字";
                    AppVersion appVersion = imp.getUpdateInfo(pkgName,appName);
                    if(appVersion != null){
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = appVersion;
                        handler.sendMessage(msg);
                    }else {
                        Log.e(TAG, "can't get app update json");
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        };
        mThread.start();
    }

    private void showForceUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        //builder.setIcon(R.drawable.icon);
        builder.setTitle("升级提示");
        builder.setMessage(mAppVersion.getMsg());
        builder.setPositiveButton("现在升级",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        downLoadApk();
                    }
                });
        builder.setNegativeButton("退出",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ((Activity)mContext).finish();
                    }
                });
        builder.setCancelable(false);
        builder.show();
    }

    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        //builder.setIcon(R.drawable.icon);
        builder.setTitle("升级提示");
        builder.setMessage(mAppVersion.getMsg());
        builder.setPositiveButton("下载",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        downLoadApk();
                    }
                });
        builder.setNegativeButton("忽略",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                });
        builder.show();
    }

    private void downLoadApk() {
        String apkUrl = mAppVersion.getURL();
        String dir = mContext.getExternalFilesDir( "apk").getAbsolutePath();
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        if(folder.exists() && folder.isDirectory()) {
            //do nothing
        }else {
            folder.mkdirs();
        }
        String filename = apkUrl.substring(apkUrl.lastIndexOf("/"),apkUrl.length());
        String destinationFilePath =  dir + "/" + filename;
        apkFile = new File(destinationFilePath);
        if(mAppVersion.isForceUpdate()){
            mProgressDialog.setCancelable(false);
        }
        mProgressDialog.show();
        Intent intent = new Intent(mContext, DownloadService.class);
        intent.putExtra("url", apkUrl);
        intent.putExtra("dest", destinationFilePath);
        intent.putExtra("receiver", new DownloadReceiver(new Handler()));
        mContext.startService(intent);
    }

    private class DownloadReceiver extends ResultReceiver {
        public DownloadReceiver(Handler handler) {
            super(handler);
        }
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            if (resultCode == DownloadService.UPDATE_PROGRESS) {
                int progress = resultData.getInt("progress");
                mProgressDialog.setProgress(progress);
                if (progress == 100) {
                    mProgressDialog.dismiss();
                    //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
                    String[] command = {"chmod","777",apkFile.toString()};
                    try{
                        ProcessBuilder builder = new ProcessBuilder(command);
                        builder.start();
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        mContext.startActivity(intent);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}