package com.gh.common.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.text.TextUtils;

import com.gh.gamecenter.core.AppExecutor;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.PlatformEntity;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.vspace.VHelper;
import com.halo.assistant.HaloApp;
import com.lightgame.download.FileUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;

import androidx.collection.ArrayMap;
import androidx.core.content.ContextCompat;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

public class PlatformUtils {

    private static PlatformUtils mInstance;

    private Context context;

    private ArrayMap<String, String> platformMap;
    private ArrayMap<String, String> platformPicUrlMap;
    private ArrayMap<String, String> platformColorMap;
    private boolean isCheck = false;
    private boolean isUpdate = false;

    private PlatformUtils(Context con) {
        this.context = con.getApplicationContext();
        initMap();
    }

    private void initMap() {
        ArrayMap<String, String> platformColorMap = new ArrayMap<>();
        platformColorMap.put("360", "#218FA4");
        platformColorMap.put("37wan", "#F5BD20");
        platformColorMap.put("91", "#6A63CB");
        platformColorMap.put("9u", "#E17237");
        platformColorMap.put("anzhi", "#58BB3D");
        platformColorMap.put("baidu", "#537CB3");
        platformColorMap.put("dangle", "#E1842B");
        platformColorMap.put("ewan", "#36A3DC");
        platformColorMap.put("gf", "#BB3D42");
        platformColorMap.put("gf-w", "#BB3D42");
        platformColorMap.put("huawei", "#EB2526");
        platformColorMap.put("mi", "#DC552B");
        platformColorMap.put("oppo", "#2A8A64");
        platformColorMap.put("ouwan", "#E6D66D");
        platformColorMap.put("pps", "#FF8C27");
        platformColorMap.put("vivo", "#3FA5E3");
        platformColorMap.put("wdj", "#5ABA3F");

        ArrayMap<String, String> platformMap = new ArrayMap<>();
        ArrayMap<String, String> platformPicUrlMap = new ArrayMap<>();

        SharedPreferences sharedPreferences = context.getSharedPreferences("gh_platform", Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("platform", null);
        if (set == null) {
            Properties properties = new Properties();
            try {
                properties.load(context.getAssets().open("platform.properties"));
                Set<String> pset = new HashSet<>();
                for (Object object : properties.keySet()) {
                    platformMap.put(object.toString(), (String) properties.get(object));
                    pset.add(object.toString() + "=" + (String) properties.get(object) + "=" + "=");
                }
                Editor editor = sharedPreferences.edit();
                editor.putStringSet("platform", pset);
                editor.apply();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            ArrayList<String> urls = new ArrayList<>();
            for (String str : set) {
                String[] platform = str.split("=");
                platformMap.put(platform[0], platform[1]);
                if (platform.length == 4 && !TextUtils.isEmpty(platform[2])) {
                    platformPicUrlMap.put(platform[0], platform[2]);
                    urls.add(platform[2]);
                }
                if (platform.length == 4 && !TextUtils.isEmpty(platform[3])) {
                    platformColorMap.put(platform[0], platform[3]);
                }
            }
            if (urls.size() != 0) {
//                checkPlatformPic(urls);
            }
        }

        updatePlatform(platformMap, platformPicUrlMap, platformColorMap);
    }

    private void checkPlatformPic(final ArrayList<String> urls) {
        isCheck = true;
        File file = new File(FileUtils.getPlatformPicDir(context));
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                for (int i = 0; i < urls.size(); i++) {
                    String url = urls.get(i);
                    String filename = url.substring(url.lastIndexOf("/") + 1);
                    if (f.getName().equals(filename)) {
                        urls.remove(i);
                        break;
                    }
                }
            }
        }
        if (urls.size() != 0) {
            AppExecutor.getIoExecutor().execute(() -> {
                int success = 0;
                for (int i = 0; i < urls.size(); i++) {
                    String url = urls.get(i);
                    String savePath = FileUtils.getPlatformPicDir(context) + File.separator + url
                            .substring(url.lastIndexOf("/") + 1);
                    int code = FileUtils.downloadFile(url, savePath);
                    if (code == HttpURLConnection.HTTP_OK) {
                        success++;
                    }
                }
                if (success == urls.size()) {
                    Handler handler = new Handler(context.getMainLooper());
                    handler.post(() -> EventBus.getDefault().post(new EBReuse("PlatformChanged")));
                }
                isCheck = false;
            });
        } else {
            isCheck = false;
        }
    }

    private void updatePlatform(ArrayMap<String, String> pMap, ArrayMap<String, String> pUMap, ArrayMap<String, String> pCMap) {
        platformMap = pMap;
        platformPicUrlMap = pUMap;
        platformColorMap = pCMap;
    }

    public static PlatformUtils getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new PlatformUtils(context);
        }
        return mInstance;
    }

    public String getPlatformColor(String platform) {
        if ("".equals(platform) || "官方版".equals(platform)) {
            return "#BB3D42";
        }
        String color = platformColorMap.get(platform);
        if (color != null) {
            return color;
        }

        int themeColor = ContextCompat.getColor(HaloApp.getInstance()
                .getApplication(), R.color.theme);
        return String.format("#%06X", 0xFFFFFF & themeColor);
    }

    public String getPlatformPicUrl(String platform) {
        return platformPicUrlMap.get(platform);
    }

    public String getPlatformName(String platform) {
        if ("".equals(platform) || "官方版".equals(platform)) {
            return "官方版";
        }

        if (VHelper.PLATFORM_V.equals(platform)) {
            return VHelper.PLATFORM_V;
        }

        String platformName = platformMap.get(platform);
        if (TextUtils.isEmpty(platformName)) {
            getPlatform();
        }
        if (!TextUtils.isEmpty(platformName)) {
            return platformName;
        }
        return platform;
    }

    public void getPlatform() {
        if (isUpdate) {
            return;
        }
        isUpdate = true;
        RetrofitManager.getInstance()
                .getApi()
                .getGamePlatform()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<PlatformEntity>>() {
                    @Override
                    public void onResponse(List<PlatformEntity> response) {
                        Set<String> platformSet = new HashSet<>();
                        for (PlatformEntity platformEntity : response) {
                            platformSet.add(platformEntity.toString());
                        }
                        SharedPreferences sp = context.getSharedPreferences("gh_platform", Context.MODE_PRIVATE);
                        sp.edit().putStringSet("platform", platformSet).apply();
                        initMap();
                        EventBus.getDefault().post(new EBReuse("PlatformChanged"));

                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                        String today = format.format(new Date());
                        sp.edit().putString("refresh_time", today).apply();
                        isUpdate = false;
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        isUpdate = false;
                    }
                });
    }

}
