package com.mjsheng.myappstore.dialog;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okserver.download.DownloadManager;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.AppDownloadInfo;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.widget.Sound;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;


public class UpdateDialog extends ShowDiaLog implements View.OnClickListener {

    private Context mContext;
    private RelativeLayout mRlUpdate;
    private TextView mTvUpdateInfo, mTvDownload;
    private Button mBtnUpdate;
    private ProgressBar mPbUpdate;
    private Sound sound;
    private AppDateInfo info = new AppDateInfo();
    private DownloadReceiver downloadReceiver;
    private AppDownloadInfo downloadInfo = null;

    public UpdateDialog(Context context) {
        super(context, R.style.password_dialog_style);
        mContext = context;
        sound = new Sound(context);
        Registeredbroadcasting();
        initDailog();
    }

    public UpdateDialog(Context context, boolean flag) {
        super(context, R.style.password_dialog_style);
        mContext = context;
        sound = new Sound(context);
        Registeredbroadcasting();
        initDailog();
        checkUpdate();
    }

    public void Registeredbroadcasting() {
        downloadReceiver = new DownloadReceiver();
        /* 注册广播 */
        IntentFilter mScreenOnFilter = new IntentFilter(Utils.DOWNLOAD_SERVICE_ACTION);
        mContext.getApplicationContext().registerReceiver(downloadReceiver, mScreenOnFilter);
    }

    public void UnregisterReceiver() {
        // 注销广播接收
        if (downloadReceiver == null)
            return;
        mContext.getApplicationContext().unregisterReceiver(downloadReceiver);
    }

    public void initDailog() {
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.update_dialog_layout, null);

        initView(view);
        setContentView(view);
    }

    private void initView(View view) {

        mRlUpdate = (RelativeLayout) view.findViewById(R.id.rl_update_up);
        mTvUpdateInfo = (TextView) view.findViewById(R.id.tv_update_info);
        mTvUpdateInfo.setText(mContext.getResources().getString(R.string.update_info_0) + Utils.getVersionName(mContext).replaceAll("[^.\\d]", ""));
        mBtnUpdate = (Button) view.findViewById(R.id.btn_update_button);
        mBtnUpdate.setOnClickListener(this);
        mPbUpdate = (ProgressBar) view.findViewById(R.id.pb_update_button);
        mTvDownload = (TextView) view.findViewById(R.id.tv_update_progress);
    }

    @Override
    public void onClick(View view) {
        sound.playSoundEffect();
        switch (view.getId()) {
            case R.id.btn_update_button:
                if (isNew == true) {//by mjsheng 是否是最新版本
                    dismiss();
                } else if (isUp == false) {
                    if (Utils.isIntent(mContext)) {
                        checkUpdate();
                    } else {
                        Utils.showToast(mContext, "请检查网络连接！");
                    }
                } else {
                    if (downloadInfo == null) {
                        sendIntent("start", info.getApp_file(), info);
                    } else {
                        if (downloadInfo.getState() == DownloadManager.FINISH) {
                            ApkUtils.install(mContext, new File(downloadInfo.getTargetPath()));
                        } else if (downloadInfo.getState() == DownloadManager.DOWNLOADING || downloadInfo.getState() == DownloadManager.WAITING) {
                            sendIntent("stop", info.getApp_file(), null);
                        } else {
                            sendIntent("start", info.getApp_file(), info);
                        }
                    }
                }
                break;
        }
    }

    private void sendIntent(String state, String URL, AppDateInfo info) {
        // 发送广播通知  下载、暂停、初始化
        if (state.equals("start")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_START_ACTION);
            msgIntent.putExtra("URL", URL);
            msgIntent.putExtra("AppDateInfo", info);
            mContext.getApplicationContext().sendBroadcast(msgIntent);
        } else if (state.equals("stop")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_STOP_ACTION);
            msgIntent.putExtra("URL", URL);
            mContext.getApplicationContext().sendBroadcast(msgIntent);
        } else if (state.equals("initialize")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_PACKAGENAME_ACTION);
            msgIntent.putExtra("packageName", mContext.getPackageName());
            mContext.getApplicationContext().sendBroadcast(msgIntent);
        } else if (state.equals("packageName")) {
            Intent msgIntent = new Intent(Utils.DOWNLOAD_PACKAGENAME_ACTION);
            msgIntent.putExtra("packageName", mContext.getPackageName());
            mContext.getApplicationContext().sendBroadcast(msgIntent);
        }
    }

    private boolean isUp = false;
    private boolean isNew = false;

    public void checkUpdate() {
        OkGo.post(Configure.HTTP_TAG_UPDATE)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .params("baoming", java.net.URLEncoder.encode(mContext.getPackageName()))
                .cacheKey(Configure.HTTP_TAG_UPDATE + java.net.URLEncoder.encode(mContext.getPackageName()))
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject person = new JSONObject(s);
                            Integer code = person.optInt("code");
                            if (code == 200) {
                                JSONArray array = person.getJSONArray("data");
                                if (array.length() >= 1) {
                                    JSONObject jsonObject = array.getJSONObject(0);
                                    info.setApp_baoming(mContext.getPackageName());
                                    info.setApp_name(jsonObject.optString("upapp_name"));
                                    info.setApp_banben(jsonObject.optString("upapp_banben"));
                                    info.setApp_file(jsonObject.optString("upapp_file"));
                                    info.setApp_size(jsonObject.optString("upapp_size"));
                                    info.setApp_desc(jsonObject.optString("upapp_desc"));
                                    // 获取packagemanager的实例
                                    PackageManager packageManager = mContext.getPackageManager();
                                    // getPackageName()是你当前类的包名，0代表是获取版本信息
                                    PackageInfo packInfo = null;
                                    try {
                                        packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
                                    } catch (PackageManager.NameNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    if (Utils.isUpdate(packInfo.versionName, info.getApp_banben()) == true) {
                                        mTvUpdateInfo.setText("发现新的版本:" + info.getApp_banben() + "(请更新)");
                                        mBtnUpdate.setText("更\t新");
                                        isUp = true;
                                    } else {
                                        mTvUpdateInfo.setText("当前版本:" + packInfo.versionName.replaceAll("[^.\\d]", "") + "(最新版本)");
                                        mBtnUpdate.setText("确\t定");
                                        isNew = true;
                                    }

                                } else {
                                    //by mjsheng
                                    mTvUpdateInfo.setText("当前版本为最新版本");
                                    mBtnUpdate.setText("确\t定");
                                    isNew = true;
                                }
                            } else {
                                mTvUpdateInfo.setText("当前版本为最新版本");
                                mBtnUpdate.setText("确\t定");
                                isNew = true;
                            }
                        } catch (Exception e) {
                            Log.e("mjsheng", "JSONException");
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCacheError(Call call, Exception e) {
                        super.onCacheError(call, e);
                        Log.e("mjsheng", "onCacheError");
                        Utils.showToast(getContext(), "网络连接不稳定，请稍后重试！");

                    }
                });

    }


    @Override
    public void dismiss() {
        super.dismiss();
        UnregisterReceiver();
    }

    //更新当前进度
    private void updateProgress(AppDownloadInfo downloadInfo) {
        if (this.downloadInfo == null) {
            mTvUpdateInfo.setVisibility(View.INVISIBLE);
            mPbUpdate.setVisibility(View.VISIBLE);
            mTvDownload.setVisibility(View.VISIBLE);
        }

        this.downloadInfo = downloadInfo;
        if (downloadInfo.getState() == DownloadManager.NONE) {
            mBtnUpdate.setText(R.string.download_continue_text);
        } else if (downloadInfo.getState() == DownloadManager.ERROR) {
            mBtnUpdate.setText(mContext.getString(R.string.download_start_text));
        } else if (downloadInfo.getState() == DownloadManager.PAUSE) {
            mBtnUpdate.setText(mContext.getString(R.string.download_continue_text));
        } else if (downloadInfo.getState() == DownloadManager.WAITING) {
            mBtnUpdate.setText(mContext.getString(R.string.download_wait_text));
        } else if (downloadInfo.getState() == DownloadManager.FINISH) {
            mBtnUpdate.setText(mContext.getString(R.string.download_install_text));
        } else if (downloadInfo.getState() == DownloadManager.DOWNLOADING) {
            mBtnUpdate.setText(mContext.getString(R.string.download_paused_text));
        } else if (downloadInfo.getState() == 10) {
            mBtnUpdate.setText("更新完成");
        }

        mTvDownload.setText((long) ((downloadInfo.getProgress() * 10000) * 1.0f / 100) + "%");
        mPbUpdate.setMax((int) downloadInfo.getTotalLength());
        mPbUpdate.setProgress((int) downloadInfo.getDownloadLength());
    }

    public class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Utils.DOWNLOAD_SERVICE_ACTION.equals(intent.getAction())) {
                AppDownloadInfo downloadInfo = (AppDownloadInfo) intent.getSerializableExtra("DownloadInfo");
                if (downloadInfo.getPackageName().equals(mContext.getPackageName()) && downloadInfo.getVersion().equals(info.getApp_banben())) {

                    updateProgress(downloadInfo); //更新进度
                }
            }
        }
    }

}
