package com.gh.common.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.view.DownloadDialog;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

public class DownloadItemUtils {

	// 初始化gameMap
	public static void initializeGameMap(Context context, ArrayMap<String, ArrayMap<String, DownloadEntity>> gameMap) {
		gameMap.clear();
		List<DownloadEntity> list = DownloadManager.getInstance(context).getAll();
		String name;
		for (int i = 0, size = list.size(); i < size; i++) {
			name = list.get(i).getName();
			ArrayMap<String, DownloadEntity> map = gameMap.get(name);
			if (map == null) {
				map = new ArrayMap<>();
				gameMap.put(name, map);
			}
			map.put(list.get(i).getPlatform(), list.get(i));
		}
	}

	// 更新下载进度条
	public static void processDate(Context context,
	                               GameEntity detailedEntity,
								   DownloadEntity downloadEntity,
								   RecyclerView.Adapter<RecyclerView.ViewHolder> adapter,
								   int index) {

		LinkedBlockingQueue<String> queue = DownloadManager.getInstance(context).getQueue(downloadEntity.getName());
		if (queue == null) {
			queue = new LinkedBlockingQueue<>();
			DownloadManager.getInstance(context).putQueue(downloadEntity.getName(), queue);
		}

		String platform = downloadEntity.getPlatform();
		ArrayMap<String, DownloadEntity> entryMap = detailedEntity.getEntryMap();

		DownloadStatus status = downloadEntity.getStatus();
		if (status.equals(DownloadStatus.pause)
				|| status.equals(DownloadStatus.cancel)
				|| status.equals(DownloadStatus.done)) {
			queue.remove(platform);
			if (entryMap == null) {
				entryMap = new ArrayMap<>();
				detailedEntity.setEntryMap(entryMap);
			}
			entryMap.put(platform, downloadEntity);
			if (!"pause".equals(DownloadManager.getInstance(context).getStatus(downloadEntity.getUrl()))) {
				adapter.notifyItemChanged(index);
			}
		} else {
			if (!queue.contains(platform)) {
				queue.offer(platform);
				if (queue.size() == 2) {
					Message msg = Message.obtain();
					msg.obj = downloadEntity.getName();
					msg.what = Constants.DOWNLOAD_ROLL;
					DownloadManager.getInstance(context).sendMessageDelayed(msg, 3000);
				}
			}
			if (platform.equals(queue.peek())) {
				if (entryMap == null) {
					entryMap = new ArrayMap<>();
					detailedEntity.setEntryMap(entryMap);
				}
				entryMap.put(platform, downloadEntity);
				if (!"pause".equals(DownloadManager.getInstance(context).getStatus(downloadEntity.getUrl()))) {
					adapter.notifyItemChanged(index);
				}
			}
		}
	}

	// 更新正常的条目，只有一个apk包
	public static void updateNormalItem(Context context,
	                                    TextView textView,
	                                    ProgressBar game_progressbar,
	                                    LinearLayout game_ll_info,
	                                    TextView download_speed,
	                                    TextView download_percentage,
	                                    TextView downloadBtn,
	                                    GameEntity entity,
	                                    boolean isShowPlatform) {

		ArrayMap<String, DownloadEntity> entryMap = entity.getEntryMap();
		if (entryMap != null && !entryMap.isEmpty()) {

			DownloadEntity downloadEntity = entryMap.get(entryMap.keyAt(0));
			if (!downloadEntity.isPluggable()
					|| entity.getApk().get(0).getPlatform().equals(downloadEntity.getPlatform())
					|| entity.getApk().get(0).getPlatform().equals("local_plugin")
					|| downloadEntity.getPlatform().equals("local_plugin")) {
				// 更改进度条和提示文本的状态
				changeStatus(context, textView, game_progressbar, game_ll_info, download_speed, download_percentage, downloadBtn,
						downloadEntity, isShowPlatform, true);
				return;
			}
		}

		textView.setVisibility(View.VISIBLE);
		game_progressbar.setVisibility(View.GONE);
		game_ll_info.setVisibility(View.GONE);

		downloadBtn.setTextColor(Color.WHITE);
		if (entity.isPluggable()) {
			downloadBtn.setText("插件化");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
		} else if (PackageManager.isInstalled(entity.getApk().get(0).getPackageName())) {
			if (PackageManager.isCanUpdate(entity.getApk().get(0).getPackageName())) {
				downloadBtn.setText("更新");
				downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
			} else {
				if (entity.getTag() != null && entity.getTag().size() != 0
						&& !PackageUtils.isSignature(context, entity.getApk().get(0).getPackageName())) {
					downloadBtn.setText("插件化");
					downloadBtn.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
				} else {
					downloadBtn.setText("启动");
					downloadBtn.setBackgroundResource(R.drawable.game_item_btn_launch_style);
				}
			}
		} else {
			downloadBtn.setText("下载");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
		}

	}

	// 更新插件的条目，有多个apk包
	public static void updatePluginItem(Context context,
	                                    TextView textView,
	                                    ProgressBar game_progressbar,
	                                    LinearLayout game_ll_info,
	                                    TextView download_speed,
	                                    TextView download_percentage,
	                                    TextView downloadBtn,
	                                    GameEntity entity,
	                                    boolean isShowPlatform) {

		ArrayMap<String, DownloadEntity> entryMap = entity.getEntryMap();

		// 更新下载按钮状态
		int doneCount = 0;      // 下载完成数量
		int updateCount = 0;    // 可更新数量
		int installCount = 0;   // 已安装数量
		int pluginCount = 0;    // 可插件化数量
		if (entryMap != null && !entryMap.isEmpty()) {
			for (String key : entryMap.keySet()) {
				if (entryMap.get(key).getStatus().equals(DownloadStatus.done)) {
					doneCount++;
				}
			}
		}

		for (ApkEntity apkEntity : entity.getApk()) {
			if (PackageManager.isCanUpdate(apkEntity.getPackageName())) {
				updateCount++;
			}
		}

		for (ApkEntity apkEntity : entity.getApk()) {
			if (PackageManager.isInstalled(apkEntity.getPackageName())) {
				if (!PackageUtils.isSignature(context, apkEntity.getPackageName())) {
					pluginCount++;
				} else {
					installCount++;
				}
			}
		}

		downloadBtn.setTextColor(Color.WHITE);
		if (doneCount != 0) {
			downloadBtn.setText("安装");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
		} else if (updateCount != 0) {
			downloadBtn.setText("更新");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
		} else if (installCount != 0) {
			downloadBtn.setText("打开");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_launch_style);
		} else if (pluginCount != 0) {
			downloadBtn.setText("插件化");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
		} else {
			downloadBtn.setText("下载");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
		}

		if (entryMap != null && !entryMap.isEmpty()) {

			DownloadEntity downloadEntity;

			LinkedBlockingQueue<String> queue = DownloadManager.getInstance(context).getQueue(entity.getName());
			if (queue != null && !queue.isEmpty()) {
				downloadEntity = entryMap.get(queue.peek());
			} else {
				downloadEntity = entryMap.get(entryMap.keyAt(0));
			}

			if (downloadEntity != null) {
				// 更改进度条和提示文本的状态
				changeStatus(context, textView, game_progressbar, game_ll_info, download_speed,
						download_percentage, downloadBtn, downloadEntity, isShowPlatform, false);
				return;
			}
		}

		textView.setVisibility(View.VISIBLE);
		game_progressbar.setVisibility(View.GONE);
		game_ll_info.setVisibility(View.GONE);
	}

	// 更改进度条和提示文本的状态
	public static void changeStatus(Context context,
	                                TextView textView,
	                                ProgressBar game_progressbar,
	                                LinearLayout game_ll_info,
	                                TextView download_speed,
	                                TextView download_percentage,
	                                TextView downloadBtn,
	                                DownloadEntity downloadEntity,
	                                boolean isShowPlatform,
	                                boolean isNormal) {
		textView.setVisibility(View.GONE);
		game_progressbar.setVisibility(View.VISIBLE);
		game_ll_info.setVisibility(View.VISIBLE);

		String platform = PlatformUtils.getInstance(context)
				.getPlatformName(downloadEntity.getPlatform());

		DownloadStatus status = downloadEntity.getStatus();
		if (status.equals(DownloadStatus.downloading)) {
			if (!"pause".equals(DownloadManager.getInstance(context).getStatus(downloadEntity.getUrl()))) {
				game_progressbar.setProgress((int) (downloadEntity.getPercent() * 10));
				if (isShowPlatform && platform != null) {
					download_speed.setText(String.format("%s - %s(剩%s)", platform,
							SpeedUtils.getSpeed(downloadEntity.getSpeed()),
							SpeedUtils.getRemainTime(downloadEntity.getSize(), downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
				} else {
					download_speed.setText(String.format("%s(剩%s)", SpeedUtils.getSpeed(downloadEntity.getSpeed()),
							SpeedUtils.getRemainTime(downloadEntity.getSize(), downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
				}
				download_percentage.setText(downloadEntity.getPercent() + "%");
			}

			if (isNormal) {
				downloadBtn.setText("下载中");
				downloadBtn.setBackgroundResource(R.drawable.game_item_btn_downloading_style);
				downloadBtn.setTextColor(context.getResources().getColorStateList(R.color.text_downloading_style));
			}
		} else if (status.equals(DownloadStatus.waiting)) {
			game_progressbar.setProgress((int) (downloadEntity.getPercent() * 10));
			if (isShowPlatform && platform != null) {
				download_speed.setText(String.format("%s - 等待", platform));
			} else {
				download_speed.setText("等待");
			}
			download_percentage.setText(downloadEntity.getPercent() + "%");

			if (isNormal) {
				downloadBtn.setText("下载中");
				downloadBtn.setBackgroundResource(R.drawable.game_item_btn_downloading_style);
				downloadBtn.setTextColor(context.getResources().getColorStateList(R.color.text_downloading_style));
			}
		} else if (status.equals(DownloadStatus.pause)
				|| status.equals(DownloadStatus.timeout)
				|| status.equals(DownloadStatus.neterror)) {
			game_progressbar.setProgress((int) (downloadEntity.getPercent() * 10));
			if (isShowPlatform && platform != null) {
				download_speed.setText(String.format("%s - 暂停", platform));
			} else {
				download_speed.setText("暂停");
			}
			download_percentage.setText(downloadEntity.getPercent() + "%");

			if (isNormal) {
				downloadBtn.setText("下载中");
				downloadBtn.setBackgroundResource(R.drawable.game_item_btn_downloading_style);
				downloadBtn.setTextColor(context.getResources().getColorStateList(R.color.text_downloading_style));
			}
		} else if (status.equals(DownloadStatus.done)) {
			game_progressbar.setProgress(1000);
			if (isShowPlatform && platform != null) {
				download_speed.setText(String.format("%s - 下载完成", platform));
			} else {
				download_speed.setText("下载完成");
			}
			download_percentage.setText(R.string.hundred_percent);

			if (isNormal) {
				downloadBtn.setText("安装");
				downloadBtn.setTextColor(Color.WHITE);
				if (downloadEntity.isPluggable()
						&& PackageManager.isInstalled(downloadEntity.getPackageName())) {
					downloadBtn.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
				} else {
					downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
				}
			}
		}
	}

	public static void updateItem(Context context,
								  TextView textView,
								  ProgressBar game_progressbar,
								  LinearLayout game_ll_info,
								  TextView download_speed,
								  TextView download_percentage,
								  TextView downloadBtn,
								  GameEntity entity,
								  boolean isShowPlatform) {

		// 控制是否显示下载按钮
		if (Config.isShow(context)) {
			downloadBtn.setVisibility(View.VISIBLE);
		} else {
			downloadBtn.setVisibility(View.GONE);
		}

		if (entity.getApk() == null || entity.getApk().isEmpty()) {
			textView.setVisibility(View.VISIBLE);
			game_progressbar.setVisibility(View.GONE);
			game_ll_info.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.GONE);
		} else if (entity.getApk().size() == 1) {
			updateNormalItem(context, textView, game_progressbar, game_ll_info, download_speed,
					download_percentage, downloadBtn, entity, isShowPlatform);
		} else {
			updatePluginItem(context, textView, game_progressbar, game_ll_info, download_speed,
					download_percentage, downloadBtn, entity, isShowPlatform);
		}

	}

	public static void updateItem(Context context,
								  TextView textView,
								  ProgressBar game_progressbar,
								  LinearLayout game_ll_info,
								  TextView download_speed,
								  TextView download_percentage,
								  TextView downloadBtn,
								  GameEntity entity) {
		updateItem(context, textView, game_progressbar, game_ll_info, download_speed,
				download_percentage, downloadBtn, entity, true);
	}

	public static void setNormalOnClickListener(final Context context,
	                                            final TextView downloadBtn,
	                                            final GameEntity entity,
	                                            final int position,
	                                            final RecyclerView.Adapter<RecyclerView.ViewHolder> adapter,
	                                            final String entrance,
	                                            final String location) {
		downloadBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String str = downloadBtn.getText().toString();
				if ("下载".equals(str)) {
					if (NetworkUtils.isWifiConnected(context)) {
						download(context, entity, downloadBtn, entrance, location);
					} else {
						DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
							@Override
							public void onConfirem() {
								download(context, entity, downloadBtn, entrance, location);
							}
						});
					}
				} else if ("插件化".equals(str)) {
					if (NetworkUtils.isWifiConnected(context)) {
						plugin(context, entity, downloadBtn, entrance, location);
					} else {
						DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
							@Override
							public void onConfirem() {
								plugin(context, entity, downloadBtn, entrance, location);
							}
						});
					}
				} else if ("安装".equals(str)) {
					install(context, entity, position, adapter);
				} else if ("启动".equals(str)) {
					Map<String, Object> kv = new HashMap<>();
					kv.put("版本", entity.getApk().get(0).getPlatform());
					DataUtils.onEvent(context, "游戏启动", entity.getName(), kv);

					PackageUtils.launchApplicationByPackageName(context, entity.getApk().get(0).getPackageName());
				} else if ("下载中".equals(str)) {
					context.startActivity(new Intent(context, DownloadManagerActivity.class));
				} else if ("更新".equals(str)) {
					if (NetworkUtils.isWifiConnected(context)) {
						update(context, entity, entrance, location);
					} else {
						DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
							@Override
							public void onConfirem() {
								update(context, entity, entrance, location);
							}
						});
					}
				}
			}
		});
	}

	public static void setPluginOnClickListener(final Context context,
	                                            final TextView downloadBtn,
	                                            final GameEntity entity,
	                                            final String entrance,
	                                            final String location) {
		downloadBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(final View v) {
				DownloadDialog.getInstance(context).showPopupWindow(v, entity, entrance, location);
			}
		});
	}

	public static void setOnClickListener(Context context,
										  TextView downloadBtn,
										  GameEntity entity,
										  int position,
										  RecyclerView.Adapter<RecyclerView.ViewHolder> adapter,
										  String entrance,
										  String location) {

		if (entity.getApk().size() == 1) {
			setNormalOnClickListener(context, downloadBtn, entity, position, adapter, entrance, location);
		} else {
			setPluginOnClickListener(context, downloadBtn, entity, entrance, location);
		}

	}

	//更新
	private static void update(Context context,
	                           GameEntity gameEntity,
	                           String entrance,
	                           String location) {
		ApkEntity apkEntity = gameEntity.getApk().get(0);
		//下载可更新游戏
		Map<String, Object> kv = new HashMap<>();
		kv.put("版本", apkEntity.getPlatform());
		kv.put("状态", "下载开始");
		DataUtils.onEvent(context, "游戏更新", gameEntity.getName(), kv);

		Map<String, Object> map = new HashMap<>();
		map.put("game", gameEntity.getName());
		map.put("game_id", gameEntity.getId());
		map.put("method", "更新");
		map.put("platform", PlatformUtils.getInstance(context)
				.getPlatformName(gameEntity.getApk().get(0).getPlatform()));
		map.put("status", "开始");
		map.put("location", location);
		map.put("entrance", entrance);
		map.put("btn_status", "更新");
		map.put("network", NetworkUtils.getConnectedType(context));
		DataCollectionManager.onEvent(context, "download", map);

		DownloadManager.createDownload(context, gameEntity, "更新", entrance, location);
	}

	//下载
	private static void download(Context context,
								 GameEntity gameEntity,
								 TextView downloadBtn,
								 String entrance,
	                             String location) {
		String msg = FileUtils.isCanDownload(gameEntity.getApk().get(0).getSize());
		if (TextUtils.isEmpty(msg)) {
			Map<String, Object> kv = new HashMap<>();
			kv.put("版本", gameEntity.getApk().get(0).getPlatform());
			kv.put("状态", "下载开始");
			DataUtils.onEvent(context, "游戏下载", gameEntity.getName(), kv);

			Map<String, Object> kv2 = new HashMap<>();
			kv2.put("版本", gameEntity.getApk().get(0).getPlatform());
			kv2.put("状态", "下载开始");
			kv2.put("位置", entrance + "-开始");
			DataUtils.onEvent(context, "游戏下载位置", gameEntity.getName(), kv2);

			Map<String, Object> kv3 = new HashMap<>();
			kv3.put(entrance, "下载数");
			kv3.put(entrance, "下载开始");
			DataUtils.onEvent(context, "应用数据", gameEntity.getName(), kv3);

			Map<String, Object> map = new HashMap<>();
			map.put("game", gameEntity.getName());
			map.put("game_id", gameEntity.getId());
			map.put("method", "正常");
			map.put("platform", PlatformUtils.getInstance(context)
					.getPlatformName(gameEntity.getApk().get(0).getPlatform()));
			map.put("status", "开始");
			map.put("location", location);
			map.put("entrance", entrance);
			map.put("btn_status", "下载");
			map.put("network", NetworkUtils.getConnectedType(context));
			DataCollectionManager.onEvent(context, "download", map);

			DownloadManager.createDownload(context, gameEntity, "下载", entrance, location);
			Toast.makeText(context, gameEntity.getName() + "已加入下载队列", Toast.LENGTH_SHORT).show();

			downloadBtn.setText("下载中");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_downloading_style);
			downloadBtn.setTextColor(context.getResources().getColorStateList(R.color.text_downloading_style));

			DownloadManager.getInstance(context).putStatus(gameEntity.getApk().get(0).getUrl(), "downloading");
		} else {
			Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
		}
	}

	//插件化
	private static void plugin(Context context,
							   GameEntity gameEntity,
							   TextView downloadBtn,
							   String entrance,
	                           String location) {
		String msg = FileUtils.isCanDownload(gameEntity.getApk().get(0).getSize());
		if (TextUtils.isEmpty(msg)) {
			Map<String, Object> kv = new HashMap<>();
			kv.put("版本", gameEntity.getApk().get(0).getPlatform());
			kv.put("状态", "下载开始");
			DataUtils.onEvent(context, "游戏下载", gameEntity.getName(), kv);

			Map<String, Object> kv2 = new HashMap<>();
			kv2.put("版本", gameEntity.getApk().get(0).getPlatform());
			kv2.put("状态", "下载开始");
			kv2.put("位置", entrance + "-开始");
			DataUtils.onEvent(context, "游戏下载位置", gameEntity.getName(), kv2);

			Map<String, Object> kv3 = new HashMap<>();
			kv3.put(entrance, "下载数");
			kv3.put(entrance, "下载开始");
			DataUtils.onEvent(context, "应用数据", gameEntity.getName(), kv3);

			Map<String, Object> map = new HashMap<>();
			map.put("game", gameEntity.getName());
			map.put("game_id", gameEntity.getId());
			map.put("method", "插件化");
			map.put("platform", PlatformUtils.getInstance(context)
					.getPlatformName(gameEntity.getApk().get(0).getPlatform()));
			map.put("status", "开始");
			map.put("location", location);
			map.put("entrance", entrance);
			map.put("btn_status", "插件化");
			map.put("network", NetworkUtils.getConnectedType(context));
			DataCollectionManager.onEvent(context, "download", map);

			DownloadManager.createDownload(context, gameEntity, "插件化", entrance, location);
			Toast.makeText(context, gameEntity.getName() + "已加入下载队列", Toast.LENGTH_SHORT).show();

			downloadBtn.setText("下载中");
			downloadBtn.setBackgroundResource(R.drawable.game_item_btn_downloading_style);
			downloadBtn.setTextColor(context.getResources().getColorStateList(R.color.text_downloading_style));

			DownloadManager.getInstance(context).putStatus(gameEntity.getApk().get(0).getUrl(), "downloading");
		} else {
			Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
		}
	}

	//安装
	private static void install(final Context context,
								GameEntity entity,
								int position,
								RecyclerView.Adapter<RecyclerView.ViewHolder> adapter) {

		DownloadEntity downloadEntity = entity.getEntryMap().get(entity.getEntryMap().keyAt(0));
		final String path = downloadEntity.getPath();
		if (FileUtils.isEmptyFile(path)) {
			Toast.makeText(context, "解析包出错（可能被误删了），请重新下载", Toast.LENGTH_SHORT).show();
			DownloadManager.getInstance(context).cancel(
					entity.getEntryMap().get(entity.getEntryMap().keyAt(0)).getUrl());
			entity.getEntryMap().remove(entity.getEntryMap().keyAt(0));
			adapter.notifyItemChanged(position);
		} else {
			PackageUtils.launchSetup(context, path);
		}
	}

}
