package com.gh.gamecenter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.base.BaseActivity;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.MD5Utils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.SpeedUtils;
import com.gh.common.util.Utils;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.entity.AppEntity;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.manager.PackageManager;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;

import org.json.JSONObject;

import java.io.File;

import de.greenrobot.event.EventBus;

/**
 * 游戏设置页面
 *
 * @author 吕方
 * @since 0814
 */
public class SettingActivity extends BaseActivity implements OnClickListener {

    public static final String TAG = SettingActivity.class.getSimpleName();

    private SwitchButton setting_sb_autoinstall, setting_sb_autodelete,
            setting_sb_deletedata, setting_sb_autoupdate;
    private TextView setting_tv_version, app_tv_speed, app_tv_percent,
            app_btn_cancel, setting_tv_cache,setting_tv_size;
    private ProgressBar app_pb_progress;

    private SharedPreferences sp;

    private Dialog dialog = null;

    private AppEntity appEntity;

    private boolean isChecking = false;
    private boolean isShowDownload = false;

    private Handler handler = new Handler();

    private int checkSizeIndex;

    private Context context = this;

    private DataWatcher dataWatcher = new DataWatcher() {
        @Override
        public void onDataChanged(DownloadEntity downloadEntity) {
            if (downloadEntity.getName().contains("光环助手") && isShowDownload) {
                app_tv_speed.setText(String.format("%s(剩%s)",
                        SpeedUtils.getSpeed(downloadEntity.getSpeed()),
                        SpeedUtils.getRemainTime(downloadEntity.getSize(), downloadEntity.getProgress(),
                                downloadEntity.getSpeed() * 1024)));
                app_pb_progress.setProgress((int) (downloadEntity.getPercent() * 10));
                app_tv_percent.setText(downloadEntity.getPercent() + "%");
                if (DownloadStatus.done.equals(downloadEntity.getStatus())) {
                    DownloadManager.getInstance(getApplicationContext())
                            .cancel(downloadEntity.getUrl(), false);
                    if (appEntity != null && appEntity.isIs_force()) {
                        AppController.getInstance().finishActivity();
                    } else {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        isShowDownload = false;
                    }
                }
            }
        }
    };

    @Override
    public void finish() {
        saveCurrentSetting();
        super.finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View contentView = View.inflate(this, R.layout.activity_setting, null);

        init(contentView, "设置");

        findViewById(R.id.setting_rl_autoinstall).setOnClickListener(this);
        findViewById(R.id.setting_rl_autodelete).setOnClickListener(this);
        findViewById(R.id.setting_rl_deletedata).setOnClickListener(this);
        findViewById(R.id.setting_rl_autoupdate).setOnClickListener(this);
        findViewById(R.id.setting_rl_update).setOnClickListener(this);
        findViewById(R.id.setting_rl_feedback).setOnClickListener(this);
        findViewById(R.id.setting_rl_cache).setOnClickListener(this);
        findViewById(R.id.setting_cv_font_size).setOnClickListener(this);

        setting_tv_version.setText("当前版本：V"
                + PackageUtils.getVersion(getApplicationContext()));

        setting_tv_cache.setText(getCacheSize());

        sp = getSharedPreferences(Config.PREFERENCE, Activity.MODE_PRIVATE);

        // 未打开下载按钮，显示修复下载按钮
        if (!sp.getBoolean("isShow", false)) {
            findViewById(R.id.setting_cv_fix_download).setVisibility(View.VISIBLE);
            findViewById(R.id.setting_cv_fix_download).setOnClickListener(this);
        }

        setting_sb_autoinstall.setChecked(sp.getBoolean("autoinstall", true));
        setting_sb_autodelete.setChecked(sp.getBoolean("autodelete", true));
        setting_sb_deletedata.setChecked(sp.getBoolean("deletedata", true));
        setting_sb_autoupdate.setChecked(sp.getBoolean("autoupdate", true));

        if (sp.getBoolean("isShowDisclaimer", false)) {
            TextView setting_tv_disclaimer = (TextView) findViewById(R.id.setting_tv_disclaimer);
            findViewById(R.id.setting_disclaimer_line).setVisibility(View.VISIBLE);
            setting_tv_disclaimer.setVisibility(View.VISIBLE);
            setting_tv_disclaimer.setOnClickListener(this);
        }

        checkSizeIndex = sp.getInt("fontsize", 1);
        if (checkSizeIndex == 0){
            checkSizeIndex = 1;
        }
        fontTextSize(checkSizeIndex);
    }

    // 获取缓存大小
    private String getCacheSize() {
        File ecDir = getExternalCacheDir();
        long cacheLength = getFolderSize(getCacheDir());
        if (ecDir != null) {
            cacheLength += getFolderSize(ecDir);
        }
        return long2Size(cacheLength);
    }

    private long getFolderSize(File folder) {
        long size = 0;
        size += folder.length();
        if (folder.isDirectory()) {
            for (File file : folder.listFiles()) {
                if (file.isDirectory()) {
                    size += getFolderSize(file);
                } else {
                    size += file.length();
                }
            }
        }
        return size;
    }

    private String long2Size(Long length) {
        float m = length / 1024f / 1024f;
        String str = Float.toString(m);
        int index = str.lastIndexOf(".");
        if (index != -1 && str.length() > index + 3) {
            str = str.substring(0, index + 3);
        }
        return str + "M";
    }

    private void saveCurrentSetting() {
        Editor mEditor = sp.edit();
        mEditor.putBoolean("autoinstall", setting_sb_autoinstall.isChecked());
        mEditor.putBoolean("autodelete", setting_sb_autodelete.isChecked());
        mEditor.putBoolean("deletedata", setting_sb_deletedata.isChecked());
        mEditor.putBoolean("autoupdate", setting_sb_autoupdate.isChecked());
        mEditor.putInt("fontsize",checkSizeIndex);
        mEditor.apply();
    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.actionbar_rl_back:
                finish();
                break;
            case R.id.setting_cv_fix_download:
                sp.edit().putBoolean("isShow", true).apply();
                toast("修复成功，快去首页看看吧");
                EventBus.getDefault().post(new EBReuse("Refresh"));
                break;
            case R.id.setting_rl_autoinstall:
                setting_sb_autoinstall.performClick();
                break;
            case R.id.setting_rl_autodelete:
                setting_sb_autodelete.performClick();
                break;
            case R.id.setting_rl_deletedata:
                setting_sb_deletedata.performClick();
                break;
            case R.id.setting_rl_autoupdate:
                setting_sb_autoupdate.performClick();
                break;
            case R.id.setting_rl_update:
                dialog = DialogUtils.showWaitDialog(this, "检查更新中...");
                if (isChecking)
                    break;
                isChecking = true;
                checkUpdate();
                break;
            case R.id.setting_rl_cache:
                DialogUtils.showWarningDialog(this, "清除缓存", "清空缓存后未安装的游戏可能需要重新下载，确定清空？",
                        new DialogUtils.ConfiremListener() {
                            @Override
                            public void onConfirem() {
                                dialog = DialogUtils.showWaitDialog(context, "清除缓存中...");
                                claerCache();
                            }
                        });
                break;
            case R.id.setting_rl_feedback:
                startActivity(new Intent(SettingActivity.this,
                        SuggestionActivity.class));
                break;
            case R.id.setting_tv_disclaimer:
                String content = sp.getString("disclaimer", null);
                if (!TextUtils.isEmpty(content)) {
                    DialogUtils.showDisclaimerDialog(this, content);
                }
                break;
            case R.id.setting_cv_font_size:
                fontSize();
                break;
            default:
                break;
        }
    }
    private void fontTextSize(int i){
        switch (i){
            case 1:
                setting_tv_size.setText("小字号");
                break;
            case 2:
                setting_tv_size.setText("中字号");
                break;
            case 3:
                setting_tv_size.setText("大字号");
                break;
            case 4:
                setting_tv_size.setText("特大字号");
                break;
        }
    }

    //设置正文字号
    private void fontSize() {
        final Dialog dialog = new Dialog(this);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_font_size, null);
        TextView tv_negative = (TextView) inflate.findViewById(R.id.font_size_negative);
        TextView tv_positive = (TextView) inflate.findViewById(R.id.font_size_positive);
        final RadioGroup radioGroup = (RadioGroup) inflate.findViewById(R.id.font_size_radiogroup);
        ((RadioButton)(radioGroup.getChildAt(checkSizeIndex-1))).setChecked(true);

        tv_negative.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        tv_positive.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                checkSizeIndex = radioGroup.getCheckedRadioButtonId() % 4;

                if (checkSizeIndex == 0){
                    checkSizeIndex = 4;
                }
                dialog.cancel();
                saveCurrentSetting();
                fontTextSize(checkSizeIndex);
            }
        });
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(inflate);
        dialog.show();
    }

    // 清除缓存
    private void claerCache() {
        new Thread() {
            @Override
            public void run() {
                long start = System.currentTimeMillis();
                deleteFolder(getCacheDir());
                deleteFolder(getExternalCacheDir());
                long time = System.currentTimeMillis() - start;
                if (time < 1000) {
                    try {
                        sleep(1000 - time);
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        setting_tv_cache.setText(getCacheSize());
                        Toast.makeText(SettingActivity.this, "缓存清除成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }.start();
    }

    private void deleteFolder(File folder) {
        if (folder != null) {
            if (folder.isDirectory()) {
                for (File file : folder.listFiles()) {
                    if (file.isDirectory()) {
                        deleteFolder(file);
                    } else {
                        file.delete();
                    }
                }
            }
            folder.delete();
        }
    }

    private void checkUpdate() {
        String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(this,
                getPackageName(), "TD_CHANNEL_ID");
        String url = Config.HOST + "v2/version?version_name="
                + PackageUtils.getVersion(getApplicationContext())
                + "&channel=" + TD_CHANNEL_ID;
        JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(url,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        isChecking = false;
                        if (dialog != null) {
                            dialog.dismiss();
                        }

                        if (response.length() == 0) {
                            toast("您的光环助手已是最新版本");
                        } else {
                            Gson gson = new Gson();
                            appEntity = gson.fromJson(response.toString(),
                                    AppEntity.class);

                            float version = Float.valueOf(appEntity
                                    .getVersion());
                            float currentVersion = Float.valueOf(PackageUtils
                                    .getVersion(getApplicationContext()));

                            if (version > currentVersion) {
                                // 光环助手 有更新
                                GameUpdateEntity game = new GameUpdateEntity();
                                game.setName("光环助手V" + appEntity.getVersion());
                                game.setPackageName(getPackageName());
                                game.setSize(appEntity.getSize());
                                game.setVersion(appEntity.getVersion());
                                game.setUrl(appEntity.getUrl());
                                game.setPlatform("官方版");
                                PackageManager.addUpdate(0, game);

                                String updateMD5 = MD5Utils.getUpdateMD5(
                                        appEntity.getUrl(),
                                        appEntity.getContent());

                                showUpdateDialog(updateMD5);
                            } else {
                                toast("已是最新版本");
                            }

                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        isChecking = false;
                        if (dialog != null) {
                            dialog.dismiss();
                        }

                        Utils.log("error = " + error.toString());

                        toast("检查更新失败");
                    }
                });
        AppController.addToRequestQueue(request, TAG);
    }

    private void showUpdateDialog(final String md5) {
        dialog = new Dialog(this);
        View view = View.inflate(this, R.layout.app_update_hint_dialog,
                null);
        TextView content = (TextView) view
                .findViewById(R.id.updeta_content);
        TextView size = (TextView) view
                .findViewById(R.id.update_app_size);
        TextView versison = (TextView) view.findViewById(R.id.update_app_version);

        versison.setText("光环助手V"+appEntity.getVersion()+"更新内容:");
        size.setText("大小："+appEntity.getSize());
        content.setText(appEntity.getContent()+"");

        if (appEntity.isIs_force()) {
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
        }
        view.findViewById(R.id.update_cannel).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (appEntity.isIs_force()) {
                            Intent data = new Intent();
                            data.putExtra("isForce", true);
                            setResult(RESULT_OK, data);
                            finish();
                        } else {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                        }
                    }
                });
        view.findViewById(R.id.updeta_confirm).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        String path = FileUtils.getDownloadPath(
                                SettingActivity.this,
                                "光环助手V" + appEntity.getVersion() + "_" + md5
                                        + ".apk");
                        File file = new File(path);
                        if (file.exists() && file.length() > 0) {
                            startActivity(PackageUtils.getInstallIntent(path));
                        } else {
                            DataUtils.onEvent(SettingActivity.this, "软件更新", "下载开始");
                            showDownloadDialog(md5);
                        }
                    }
                });
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        dialog.show();
    }

    private void showDownloadDialog(String md5) {
        dialog = new Dialog(SettingActivity.this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.closeOptionsMenu();
        View view = View.inflate(this, R.layout.app_updating_dialog, null);

        app_pb_progress = (ProgressBar) view.findViewById(R.id.app_pb_progress);
        app_tv_speed = (TextView) view.findViewById(R.id.app_tv_speed);
        app_tv_percent = (TextView) view.findViewById(R.id.app_tv_percent);
        app_btn_cancel = (TextView) view.findViewById(R.id.app_tv_cancel);

        app_btn_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DownloadManager.getInstance(getApplicationContext()).cancel(
                        appEntity.getUrl());
                if (appEntity.isIs_force()) {
                    Intent data = new Intent();
                    data.putExtra("isForce", true);
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    isShowDownload = false;
                }
            }
        });

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        dialog.show();

        isShowDownload = true;

        String path = FileUtils.getDownloadPath(SettingActivity.this, "光环助手V"
                + appEntity.getVersion() + "_" + md5 + ".apk");

        File file = new File(path);

        if (file.exists()) {
            file.delete();
        }

        DownloadEntity downloadEntity = new DownloadEntity();
        downloadEntity.setUrl(appEntity.getUrl());
        downloadEntity.setName("光环助手V" + appEntity.getVersion());
        downloadEntity.setPath(path);
        downloadEntity.setPlatform("官方版");
        downloadEntity.setPackageName(getPackageName());

        DownloadManager.getInstance(getApplicationContext()).cancel(
                downloadEntity.getUrl(), false);

        DownloadManager.getInstance(getApplicationContext()).pauseAll();

        DownloadManager.getInstance(getApplicationContext()).add(downloadEntity);
    }

    @Override
    public void onResume() {
        super.onResume();
        DownloadManager.getInstance(SettingActivity.this).addObserver(
                dataWatcher);
    }

    @Override
    public void onPause() {
        saveCurrentSetting();
        super.onPause();
        DownloadManager.getInstance(SettingActivity.this).removeObserver(
                dataWatcher);
    }

    @Override
    protected void onDestroy() {
        saveCurrentSetting();
        super.onDestroy();
        AppController.canclePendingRequests(TAG);
        setting_sb_autoinstall = null;
        setting_sb_autodelete = null;
        setting_sb_deletedata = null;
        setting_sb_autoupdate = null;
        setting_tv_version = null;
        app_tv_speed = null;
        app_tv_percent = null;
        app_btn_cancel = null;
        setting_tv_cache = null;
        app_pb_progress = null;
        sp = null;
        dialog = null;
        appEntity = null;
        handler = null;
        dataWatcher = null;
    }
}
