package com.gh.common.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;

import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import de.greenrobot.event.EventBus;

public class PlatformUtils {

	private static PlatformUtils mInstance;

	private Context context;

	private ArrayMap<String, String> platformMap;
	private ArrayMap<String, Integer> platformPicMap;
	private ArrayMap<String, String> platformPicUrlMap;
	private ArrayMap<String, String> platformColorMap;

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

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

	private void initMap() {
		ArrayMap<String, Integer> platformPicMap = new ArrayMap<String, Integer>();
		platformPicMap.put("360", R.drawable.platform_360);
		platformPicMap.put("37wan", R.drawable.platform_37);
		platformPicMap.put("91", R.drawable.platform_91);
		platformPicMap.put("9u", R.drawable.platform_9u);
		platformPicMap.put("anzhi", R.drawable.platform_anzhi);
		platformPicMap.put("baidu", R.drawable.platform_baidu);
		platformPicMap.put("dangle", R.drawable.platform_dl);
		platformPicMap.put("ewan", R.drawable.platform_ewan);
		platformPicMap.put("gf", R.drawable.platform_gf);
		platformPicMap.put("gf-w", R.drawable.platform_gfw);
		platformPicMap.put("huawei", R.drawable.platform_hw);
		platformPicMap.put("mi", R.drawable.platform_mi);
		platformPicMap.put("oppo", R.drawable.platform_oppo);
		platformPicMap.put("ouwan", R.drawable.platform_ouwan);
		platformPicMap.put("pps", R.drawable.platform_pps);
		platformPicMap.put("vivo", R.drawable.platform_vivo);
		platformPicMap.put("wdj", R.drawable.platform_wdj);

		ArrayMap<String, String> platformColorMap = new ArrayMap<String, String>();
		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<String, String>();
		ArrayMap<String, String> platformPicUrlMap = new ArrayMap<String, String>();

		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<String>();
				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<String>();
			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);
			}
		}

		updataPlatform(platformMap, platformPicMap, platformPicUrlMap,
				platformColorMap);
	}

	private boolean isCheck = false;

	private void updataPlatform(ArrayMap<String, String> pMap,
			ArrayMap<String, Integer> pPMap, ArrayMap<String, String> pUMap,
			ArrayMap<String, String> pCMap) {
		platformMap = pMap;
		platformPicMap = pPMap;
		platformPicUrlMap = pUMap;
		platformColorMap = pCMap;
	}

	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) {
			new Thread() {
				@Override
				public void run() {
					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);
						try {
							int code = FileUtils.downloadFile(url, savePath);
							if (code == HttpStatus.SC_OK) {
								success++;
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (success == urls.size()) {
						Handler handler = new Handler(context.getMainLooper());
						handler.post(new Runnable() {
							@Override
							public void run() {
								EventBus.getDefault().post(new EBReuse("PlatformChanged"));
							}
						});
					}
					isCheck = false;
				}
			}.start();
		} else {
			isCheck = false;
		}
	}

	public ArrayMap<String, String> getPlatformMap() {
		return platformMap;
	}

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

	public int getPlatformPic(String platform) {
		if ("".equals(platform) || "官方版".equals(platform)
				|| "local_plugin".equals(platform)) {
			return R.drawable.platform_gf;
		}
		Integer id = platformPicMap.get(platform);
		if (id != null) {
			return id;
		}
		return 0;
	}

	public String getPlatformPicPath(String platform) {
		String path = null;
		String url = platformPicUrlMap.get(platform);
		if (url != null) {
			String fileName = url.substring(url.lastIndexOf("/") + 1);
			File file = new File(FileUtils.getPlatformPicDir(context));
			if (file.isDirectory()) {
				for (File f : file.listFiles()) {
					if (f.getName().equals(fileName)) {
						path = f.getAbsolutePath();
						break;
					}
				}
			}
			if (path == null && !isCheck) {
				ArrayList<String> urls = new ArrayList<String>();
				for (String value : platformPicUrlMap.values()) {
					urls.add(value);
				}
				checkPlatformPic(urls);
			}
		}
		return path;
	}

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

	boolean isUpdate = false;

	public void getPlatform() {
		if (isUpdate) {
			return;
		}
		isUpdate = true;
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
				TimestampUtils.addTimestamp(Config.HOST + "v1d45/support/setting/platform",
						Constants.PLATFORM_CD),
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						try {
							Set<String> pset = new HashSet<String>();
							for (int i = 0; i < response.length(); i++) {
								JSONObject jsonObject = response
										.getJSONObject(i);
								String code = jsonObject.getString("code");
								String name = jsonObject.getString("name");
								String pic = jsonObject.getString("pic");
								String color = jsonObject.getString("color");
								pset.add(code + "=" + name + "=" + pic + "="
										+ color);
							}
							SharedPreferences sharedPreferences = context
									.getSharedPreferences("gh_platform",
											Context.MODE_PRIVATE);
							Editor editor = sharedPreferences.edit();
							editor.putStringSet("platform", pset);
							editor.apply();
							initMap();
							EventBus.getDefault().post(new EBReuse("PlatformChanged"));
						} catch (JSONException e) {
							e.printStackTrace();
						}
						isUpdate = false;
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						isUpdate = false;
					}
				});
		AppController.addToRequestQueue(request);
	}

}
