package com.gh.gamecenter.game;

import android.content.Context;
import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.NoConnectionError;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
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.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.DownloadItemUtils;
import com.gh.common.util.GameViewUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.view.CardLinearLayout;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNormalViewHolder;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.listener.OnCallBackListener;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.GameManager;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author 温冠超
 * @email 294299195@qq.com
 * @date 2015-8-8
 * @update 2015-8-11
 * @des 首页插件fragment适配器
 */

public class Game3FragmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

	private Game3Fragment fragment;
	private Context context;
	private OnCallBackListener listener;

	private boolean isRemove;
	private boolean isLoading;
	private boolean isNetworkError;

	private List<GameEntity> list;

	// 黄壮华 获取引用 修改2015/8/15
	private ArrayMap<String, Integer> locationMap;
	private ArrayMap<String, String> nameMap;

	// 黄壮华 获取引用 修改2015/8/15
	public Game3FragmentAdapter(Game3Fragment fment, boolean isLoad) {

		this.fragment = fment;
		this.context = fment.getActivity();
		this.listener = fment;

		locationMap = new ArrayMap<>();
		nameMap = new ArrayMap<>();

		isRemove = false;
		isLoading = false;
		isNetworkError = false;

		list = new ArrayList<>();

		if (isLoad) {
			load();
		}
	}

	public ArrayMap<String, Integer> getLocationMap() {
		return locationMap;
	}

	public ArrayMap<String, String> getNameMap() {
		return nameMap;
	}

	public void load() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				addList(0);
			}
		}){}.start();
	}

	public void addList(final int offset) {
		if (isLoading) {
			return;
		}
		isLoading = true;
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
				TimestampUtils.addTimestamp(
						Config.HOST + "v1d50/game/danjiyouxi?limit=20&offset=" + offset,
						Constants.GAME_CD),
				new Response.Listener<JSONArray>() {

					@Override
					public void onResponse(JSONArray response) {
						processingData(response, offset);
						isLoading = false;
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						isLoading = false;
						// 无网络连接
						if (error.getClass().equals(NoConnectionError.class)
								|| error.getClass().equals(TimeoutError.class)) {
							if (offset == 0) {
								listener.loadError();
							} else {
								Toast.makeText(context, "加载失败，请检查网络状态", Toast.LENGTH_SHORT).show();
								isNetworkError = true;
								notifyItemChanged(getItemCount() - 1);
							}
						}
					}

				});
		AppController.addToRequestQueue(request, Game3Fragment.TAG);
	}

	private void processingData(JSONArray response, int offset) {
		Type listType = new TypeToken<ArrayList<GameEntity>>() {}.getType();
		Gson gson = new Gson();
		List<GameEntity> gameList = gson.fromJson(response.toString(), listType);
		if (gameList != null && !gameList.isEmpty()) {
			if (!list.isEmpty()) {
				for (int i = 0; i < gameList.size(); i++) {
					GameEntity entity = gameList.get(i);
					// 去重
					for (int j = 0; j < list.size(); j++) {
						if (list.get(j).getId().equals(entity.getId())) {
							gameList.remove(i);
							i--;
							break;
						}
					}
				}
			}
			GameManager manager = new GameManager(context);
			for (GameEntity entity : gameList) {
				// 黄壮华 初始化游戏状态 修改2015/8/15
				entity.setEntryMap(DownloadManager.getInstance(context).getEntryMap(entity.getName()));
				manager.addOrUpdate(entity.getApk(), entity.getId(), entity.getName());
			}
			list.addAll(gameList);
			if (!fragment.isHidden() && !fragment.isEverpause()) {
				notifyItemRangeInserted(list.size() - gameList.size(), gameList.size());
			}
		}

		if (fragment.isHidden() || fragment.isEverpause()) {
			notifyDataSetChanged();
		}

		listener.loadDone();

		if (gameList == null || gameList.isEmpty() || (offset == 0 && gameList.size() < 20)) {
			isRemove = true;
			notifyItemChanged(getItemCount() - 1);
		}

		// 黄壮华 获取游戏位置信息 修改2015/8/15
		for (int i = 0, size = list.size(); i < size; i++) {
			GameEntity entity = list.get(i);
			locationMap.put(entity.getName(), i);
			for (ApkEntity apkEntity : entity.getApk()) {
				nameMap.put(apkEntity.getPackageName(), entity.getName());
			}
		}
	}

	@Override
	public int getItemCount() {
		if (list.size() == 0) {
			return 0;
		}
		return list.size() + 1;
	}

	@Override
	public int getItemViewType(int position) {
		return position;
	}

	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
		if (i == list.size()) {
			View view = LayoutInflater.from(viewGroup.getContext()).inflate(
					R.layout.refresh_footerview, viewGroup, false);
			return new FooterViewHolder(view);
		} else {
			View view = LayoutInflater.from(viewGroup.getContext()).inflate(
					R.layout.game_normal_item, viewGroup, false);
			return new GameNormalViewHolder(view);
		}
	}

	@Override
	public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
		if (viewHolder instanceof GameNormalViewHolder) {
			initGameNormalViewHolder((GameNormalViewHolder) viewHolder, list.get(position), position);
		} else if (viewHolder instanceof FooterViewHolder) {
			initFooterViewHolder((FooterViewHolder) viewHolder);
		}
	}

	private void initGameNormalViewHolder(final GameNormalViewHolder holder, final GameEntity gameEntity, int position) {

		// 第一个
		if (position == 0) {
			((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
		} else {
			((CardLinearLayout) holder.itemView).setmTop(0);
		}

		// 最后一个
		if (position == list.size() - 1) {
			((CardLinearLayout) holder.itemView).setBottom(true);
		} else {
			((CardLinearLayout) holder.itemView).setBottom(false);
		}

		ImageUtils.getInstance(context).display(gameEntity.getIcon(), holder.gameThumb);
		holder.gameNameAndSize.setText(gameEntity.getName());
		if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
			holder.gameDes.setText(gameEntity.getBrief());
		} else {
			gameEntity.getApk().get(0).setPlatform("local_plugin");
			holder.gameDes.setText(String.format("%s  %s", gameEntity.getApk().get(0).getSize(), gameEntity.getBrief()));
		}

		GameViewUtils.setLabelList(context, holder.labelList, gameEntity.getTag());

		holder.itemView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Map<String, Object> kv = new HashMap<>();
				kv.put("名字", gameEntity.getName());
				kv.put("位置", String.valueOf(holder.getPosition() + 1));
				DataUtils.onEvent(context, "点击", "游戏-单机", kv);

				Map<String, Object> map = new HashMap<>();
				map.put("location", "列表");
				map.put("page", "游戏-单机");
				map.put("game", gameEntity.getName());
				map.put("game_id", gameEntity.getId());
				DataCollectionManager.onEvent(context, "click-item", map);

				AppController.put("GameEntity", gameEntity);
				Intent intent = new Intent(context, GameDetailActivity.class);
				intent.putExtra("entrance", "(游戏-单机)");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
		});

		DownloadItemUtils.setOnClickListener(context, holder.downloadBtn,
				gameEntity, position, this, "(游戏-单机)",
				"游戏-单机:" + gameEntity.getName());

		DownloadItemUtils.updateItem(context, holder.gameDes,
				holder.game_progressbar, holder.game_ll_info,
				holder.download_speed, holder.download_percentage,
				holder.downloadBtn, gameEntity, false);
	}

	private void initFooterViewHolder(FooterViewHolder holder) {
		if (isNetworkError) {
			holder.footerview_line1.setVisibility(View.GONE);
			holder.footerview_line2.setVisibility(View.GONE);
			holder.footerview_progressbar.setVisibility(View.GONE);
			holder.footerview_tv_loading.setText("加载失败，点击重试");
			holder.itemView.setClickable(true);
			holder.itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					isNetworkError = false;
					notifyItemChanged(getItemCount() - 1);
					addList(list.size());
				}
			});
		} else if (isRemove) {
			holder.footerview_line1.setVisibility(View.VISIBLE);
			holder.footerview_line2.setVisibility(View.VISIBLE);
			holder.footerview_progressbar.setVisibility(View.GONE);
			holder.footerview_tv_loading.setText("到底了哦~");
			holder.itemView.setClickable(false);
		} else {
			holder.footerview_line1.setVisibility(View.GONE);
			holder.footerview_line2.setVisibility(View.GONE);
			holder.footerview_progressbar.setVisibility(View.VISIBLE);
			holder.footerview_tv_loading.setText("加载中...");
			holder.itemView.setClickable(false);
		}
	}

	public List<GameEntity> getList() {
		return list;
	}

	public boolean isRemove() {
		return isRemove;
	}

	public void setRemove(boolean isRemove) {
		this.isRemove = isRemove;
	}

	public boolean isLoading() {
		return isLoading;
	}

	public boolean isNetworkError() {
		return isNetworkError;
	}

	public void setNetworkError(boolean isNetworkError) {
		this.isNetworkError = isNetworkError;
	}

}
