package com.gh.common.constant;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.gh.common.util.AdHelper;
import com.gh.common.util.PackageHelper;
import com.gh.common.util.PackageUtils;
import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.common.constant.CommonConsts;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.retrofit.BiResponse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.utils.DarkModeUtils;
import com.gh.gamecenter.common.utils.EnvHelper;
import com.gh.gamecenter.core.utils.GsonUtils;
import com.gh.gamecenter.core.utils.SPUtils;
import com.gh.gamecenter.core.utils.UrlFilterUtils;
import com.gh.gamecenter.entity.GameGuidePopupEntity;
import com.gh.gamecenter.entity.NewApiSettingsEntity;
import com.gh.gamecenter.entity.NewSettingsEntity;
import com.gh.gamecenter.entity.VSetting;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.feature.entity.SettingsEntity;
import com.gh.gamecenter.feature.entity.SimulatorEntity;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.vspace.VHelper;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class Config {

    // 这个 API_HOST 在测试包里会随着选择的环境切换，正式包里会一直保持正式 host
    public static final String API_HOST = EnvHelper.getHost();
    public static final String NEW_API_HOST = EnvHelper.getNewHost();
    public static final String VAPI_HOST = EnvHelper.getVHost();

    // Third-Party confs
    public static final String WECHAT_APPID = BuildConfig.WECHAT_APPID;
    public static final String WECHAT_SECRET = BuildConfig.WECHAT_SECRET;
    public static final String TENCENT_APPID = BuildConfig.TENCENT_APPID;
    public static final String WEIBO_APPKEY = BuildConfig.WEIBO_APPKEY;
    public static final String QUICK_LOGIN_APPID = BuildConfig.QUICK_LOGIN_APPID;
    public static final String QUICK_LOGIN_APPKEY = BuildConfig.QUICK_LOGIN_APPKEY;
    // http://www.ghzs666.com/article/${articleId}.html
    public static final String URL_ARTICLE = "http://www.ghzs666.com/article/"; // ghzs/ghzs666 统一

    private static final String SETTINGS_KEY = "settingsKey";

    private static SettingsEntity mSettingsEntity;
    private static NewSettingsEntity mNewSettingsEntity;
    private static NewApiSettingsEntity mNewApiSettingsEntity;

    private static NewApiSettingsEntity.NightMode mNightModeSetting;
    private static SimulatorEntity mNewSimulatorEntity;
    private static VSetting mVSetting;
    private static GameGuidePopupEntity mGameGuidePopupEntity;
    private static SharedPreferences mDefaultSharedPreferences;

    public static final String FIX_DOWNLOAD_KEY = "isFixDownload";
    public static final String FIX_PLUGIN_KEY = "isFixPlugin";

    public static final int VIDEO_PAGE_SIZE = 21; // 视频列表大多都是一行3个

    public static boolean isShow() {
        if (SPUtils.getBoolean(Constants.SP_TEENAGER_MODE)) return false;

        if (getPreferences().getBoolean(FIX_DOWNLOAD_KEY, false)) return true;

        if (!isExistDownloadFilter()) return false;

        for (SettingsEntity.Download entity : getSettings().getDownload()) {
            if ("all".equals(entity.getGame())) {
                if (entity.getPluginfy() && "normal".equals(entity.getPolicy()) && filterTime(entity.getTime())) {
                    return true;
                }
            }
        }
        return false;
    }


    public static boolean isShowDownload(String gameId) {

        if (getPreferences().getBoolean(FIX_DOWNLOAD_KEY, false)) return true;

        if (TextUtils.isEmpty(gameId) || !isExistDownloadFilter())
            return false;

        for (SettingsEntity.Download entity : getSettings().getDownload()) {
            if (gameId.equals(entity.getGame())) {
                if ("normal".equals(entity.getPolicy()) && filterTime(entity.getTime())) {
                    return true;
                } else {
                    return false;
                }
            } else if ("all".equals(entity.getGame())) {
                if ("normal".equals(entity.getPolicy()) && filterTime(entity.getTime())) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 是否启用畅玩游戏
     */
    public static boolean isVGameEnabled() {
        if (getSettings() == null) {
            return false;
        }

        return !"off".equals(getSettings().getGameSmooth());
    }

    /**
     * VPN 开关选项是否开启
     */
    public static boolean isVpnOptionEnabled() {
        if (mNewApiSettingsEntity == null
                || mNewApiSettingsEntity.getInstall() == null
                || mNewApiSettingsEntity.getInstall().getVpnRequired() == null) {
            return false;
        }

        return mNewApiSettingsEntity.getInstall().getVpnRequired().getShouldShowVpnOption();
    }

    public static boolean isShowPlugin(String gameId) {
        SharedPreferences preferences = getPreferences();
        boolean isFixPlugin = preferences.getBoolean(FIX_PLUGIN_KEY, false);
        if (isFixPlugin) return true;

        if (TextUtils.isEmpty(gameId) || !isExistDownloadFilter())
            return false;

        for (SettingsEntity.Download entity : getSettings().getDownload()) {
            if (gameId.equals(entity.getGame())) {
                if (entity.getPluginfy() && filterTime(entity.getTime())) {
                    return true;
                } else {
                    return false;
                }
            }

            if ("all".equals(entity.getGame())) {
                if (entity.getPluginfy() && filterTime(entity.getTime())) {
                    preferences.edit().putBoolean(FIX_PLUGIN_KEY, true).apply();
                    return true;
                }
            }
        }

        return false;
    }

    public static boolean isShowPlugin() {
        SharedPreferences preferences = getPreferences();
        boolean isFixPlugin = preferences.getBoolean(FIX_PLUGIN_KEY, false);
        if (isFixPlugin) return true;

        if (!isExistDownloadFilter())
            return false;

        for (SettingsEntity.Download entity : getSettings().getDownload()) {
            if ("all".equals(entity.getGame())) {
                if (entity.getPluginfy() && filterTime(entity.getTime())) {
                    preferences.edit().putBoolean(FIX_PLUGIN_KEY, true).apply();
                    return true;
                }
            }
        }

        return false;
    }

    private static boolean filterTime(SettingsEntity.Download.TimeEntity timeEntity) {
        long end = timeEntity.getEnd();
        long start = timeEntity.getStart();
        long curTime = Utils.getTime(HaloApp.getInstance().getApplication());

        if ((start == 0 || curTime >= start) && (end == 0 || curTime <= end)) {
            return true;
        }

        return false;
    }

    public static void setSettings(SettingsEntity settingsEntity) {
        getPreferences().edit().putString(SETTINGS_KEY, GsonUtils.toJson(settingsEntity)).apply();
        mSettingsEntity = settingsEntity;

        // 更新设置状态
        mSettingsEntity.showArticleEntrance();
        mSettingsEntity.showCommunityEntrance();

        // 加载完设置后刷新下
        PackageHelper.initList();

        // 初始化畅玩相关的东西
        VHelper.init(HaloApp.getInstance());
    }

    @Nullable
    public static SettingsEntity getSettings() {
        if (mSettingsEntity == null) {
            try {
                String json = getPreferences().getString(SETTINGS_KEY, null);
                if (!TextUtils.isEmpty(json)) {
                    mSettingsEntity = GsonUtils.fromJson(json, SettingsEntity.class);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mSettingsEntity;
    }

    //新模拟器
    @Nullable
    public static SimulatorEntity getNewSimulatorEntitySetting() {
        if (mNewSimulatorEntity != null) {
            return mNewSimulatorEntity;
        } else if (mNewApiSettingsEntity != null && mNewApiSettingsEntity.getSimulator() != null) {
            return mNewApiSettingsEntity.getSimulator();
        } else {
            return null;
        }
    }

    @Nullable
    public static NewApiSettingsEntity.NightMode getNightModeSetting() {
        if (mNightModeSetting != null) {
            return mNightModeSetting;
        } else if (mNewApiSettingsEntity != null && mNewApiSettingsEntity.getNightMode() != null) {
            return mNewApiSettingsEntity.getNightMode();
        } else {
            return null;
        }
    }

    public static boolean getUserInterestedGame() {
        if (mNewApiSettingsEntity != null) {
            return mNewApiSettingsEntity.getUserInterestedGame();
        } else {
            return false;
        }
    }

    @Nullable
    public static NewSettingsEntity getNewSettingsEntity() {
        if (mNewSettingsEntity == null) {
            try {
                String json = SPUtils.getString(Constants.SP_NEW_SETTINGS);
                if (!TextUtils.isEmpty(json)) {
                    mNewSettingsEntity = GsonUtils.fromJson(json, NewSettingsEntity.class);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mNewSettingsEntity;
    }

    @Nullable
    public static NewApiSettingsEntity getNewApiSettingsEntity() {
        if (mNewApiSettingsEntity == null) {
            try {
                String json = SPUtils.getString(Constants.SP_NEW_API_SETTINGS);
                if (!TextUtils.isEmpty(json)) {
                    mNewApiSettingsEntity = GsonUtils.fromJson(json, NewApiSettingsEntity.class);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mNewApiSettingsEntity;
    }

    public static void updateNewApiSettings(NewApiSettingsEntity settingsEntity) {
        mNewApiSettingsEntity = settingsEntity;
        SPUtils.setString(Constants.SP_NEW_API_SETTINGS, GsonUtils.toJson(settingsEntity));
    }

    @Nullable
    public static VSetting getVSettingEntity() {
        if (mVSetting == null) {
            try {
                String json = SPUtils.getString(Constants.SP_V_SETTINGS);
                if (!TextUtils.isEmpty(json)) {
                    mVSetting = GsonUtils.fromJson(json, VSetting.class);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mVSetting;
    }

    @Nullable
    public static GameGuidePopupEntity getGameGuidePopupEntity() {
        return mGameGuidePopupEntity;
    }

    private static boolean isExistDownloadFilter() {
        if (getSettings() == null || getSettings().getDownload() == null || getSettings().getDownload().size() == 0) {
            return false;
        } else {
            return true;
        }
    }

    public static void filterPluginArticle(List<NewsEntity> list) {
        if (isShowPlugin() || list == null) return;

        for (int i = 0; i < list.size(); i++) {
            NewsEntity newsEntity = list.get(i);
            String title = newsEntity.getTitle();
            if (!TextUtils.isEmpty(title) && title.contains("插件")) {
                list.remove(i);
                i--;
            }
        }
    }

    public static SharedPreferences getPreferences() {
        if (mDefaultSharedPreferences == null) {
            mDefaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().getApplication());
        }

        return mDefaultSharedPreferences;
    }

    @SuppressLint("CheckResult")
    public static void getGhzsSettings() {
        String channel = HaloApp.getInstance().getChannel();

        // 把请求提前，避免请求过多阻塞，首页显示广告时老是用到上一次的缓存
        getNewSettings(channel);

        RetrofitManager.getInstance()
                .getApi().getSettings(PackageUtils.getGhVersionName(), channel)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<SettingsEntity>() {
                    @Override
                    public void onResponse(SettingsEntity response) {
                        Config.setSettings(response);

                        // 意见反馈
                        SharedPreferences.Editor edit = getPreferences().edit();
                        edit.putString(CommonConsts.SUGGESTION_HINT_TYPE,
                                GsonUtils.toJson(response.getSuggestion()));
                        edit.apply();

                        if (!getPreferences().getBoolean(Config.FIX_DOWNLOAD_KEY, false) && Config.isShow()) {
                            getPreferences().edit().putBoolean(Config.FIX_DOWNLOAD_KEY, true).apply();
                        }
                        if (!SPUtils.getBoolean(Constants.SP_TEENAGER_MODE)) {
                            EventBus.getDefault().post(new EBReuse("Refresh"));
                        }
                    }
                });

        RetrofitManager.getInstance()
                .getApi().getNewSettings(Build.MANUFACTURER, Build.MODEL, channel, Build.VERSION.SDK_INT, BuildConfig.VERSION_NAME)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BiResponse<NewSettingsEntity>() {
                    @Override
                    public void onSuccess(NewSettingsEntity data) {
                        mNewSettingsEntity = data;
                        SPUtils.setString(Constants.SP_NEW_SETTINGS, GsonUtils.toJson(data));
                    }
                });

        RetrofitManager.getInstance()
                .getVApi().getSettings(BuildConfig.VERSION_NAME)
                .subscribeOn(Schedulers.io())
                .subscribe(new BiResponse<VSetting>() {
                    @Override
                    public void onSuccess(VSetting data) {
                        mVSetting = data;
                        SPUtils.setString(Constants.SP_V_SETTINGS, GsonUtils.toJson(data));
                    }
                });

        RetrofitManager.getInstance()
                .getApi().getGameGuidePopup(Build.MANUFACTURER, Build.VERSION.RELEASE, Build.MODEL, channel, BuildConfig.VERSION_NAME)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BiResponse<GameGuidePopupEntity>() {
                    @Override
                    public void onSuccess(GameGuidePopupEntity data) {
                        mGameGuidePopupEntity = data;
                    }
                });

        String manufacturer = Build.MANUFACTURER.toUpperCase(Locale.CHINA);
        if (manufacturer.equals("OPPO") || manufacturer.equals("VIVO")) {
            RetrofitManager.getInstance().getNewApi().getBrowserHintUrl(manufacturer)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BiResponse<ResponseBody>() {
                        @Override
                        public void onSuccess(ResponseBody data) {
                            try {
                                JSONObject jsonObject = new JSONObject(data.string());
                                if (!TextUtils.isEmpty(jsonObject.getJSONObject("data").getString("link"))) {
                                    SPUtils.setString(Constants.SP_BROWSER_HINT_URL, jsonObject.getJSONObject("data").getString("link"));
                                }
                            } catch (JSONException | IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
    }

    @SuppressLint("CheckResult")
    private static void getNewSettings(String channel) {
        if (mNewApiSettingsEntity == null) {

            String filterString = UrlFilterUtils.getFilterQuery(
                    "manufacturer", Build.MANUFACTURER,
                    "model", Build.MODEL,
                    "android_sdk_version", String.valueOf(Build.VERSION.SDK_INT));

            RetrofitManager.getInstance()
                    .getNewApi().getNewSettings(PackageUtils.getGhVersionName(), channel, filterString)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BiResponse<NewApiSettingsEntity>() {
                        @Override
                        public void onSuccess(NewApiSettingsEntity data) {
                            mNewApiSettingsEntity = data;
                            mNightModeSetting = data.getNightMode();
                            mNewSimulatorEntity = data.getSimulator();
                            if (HaloApp.getInstance().isNewForThisVersion && mNightModeSetting != null && mNightModeSetting.getInstall()) {
                                DarkModeUtils.INSTANCE.updateFollowSystemDarkModeToSp(true);
                                DarkModeUtils.INSTANCE.initDarkMode();
                            }
                            AdHelper.prefetchStartUpAd(mNewApiSettingsEntity);
                            SPUtils.setString(Constants.SP_NEW_API_SETTINGS, GsonUtils.toJson(data));
                        }
                    });
        }
    }
}
