package com.gh.gamecenter.adapter;

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.SubjectActivity;
import com.gh.gamecenter.adapter.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNormalViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameTestViewHolder;
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.Date;
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 SubjectAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

	private Context context;
	private OnCallBackListener listener;

	private List<GameEntity> list;
	private boolean order;
	private static final int FOOTER_ITEM = 101;
	private boolean isLoaded;

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

	private String id;
	private String name;
	private String entrance;

	private boolean isRemove;
	private boolean isNetworkError;

	public SubjectAdapter(SubjectActivity activity, String id, String name, boolean order, String entrance) {

		this.context = activity;
		this.listener = activity;

		this.id = id;
		this.name = name;
		this.order = order;
		this.entrance = entrance;

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

		list = new ArrayList<>();
		isLoaded = false;
		isNetworkError = false;

		initList(1);
	}

	public void initList(final int page) {
		isLoaded = false;
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
				TimestampUtils.addTimestamp(
						Config.HOST + "v1d50/game/column/" + id + "?page=" + page,
						Constants.GAME_CD),
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						processingData(response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// 无网络连接
						if (error.getClass().equals(NoConnectionError.class)
								|| error.getClass().equals(TimeoutError.class)) {
							if (page == 1){
								if (listener != null) {
									listener.loadError();
								}
							}else {
								Toast.makeText(context, "加载失败，请检查网络状态", Toast.LENGTH_SHORT).show();
								isNetworkError = true;
								notifyDataSetChanged();
							}

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

	private void processingData(JSONArray response) {
		Type listType = new TypeToken<ArrayList<GameEntity>>() {}.getType();
		Gson gson = new Gson();
		GameManager manager = new GameManager(context);
		List<GameEntity> gameList = gson.fromJson(response.toString(), listType);
		if (gameList != null && !gameList.isEmpty()) {
			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);

			notifyItemRangeInserted(list.size() - gameList.size(), gameList.size());
		}

		// 黄壮华 获取游戏位置信息 修改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());
			}
		}

		if (listener != null) {
			listener.loadDone();
		}
		if (list.isEmpty() || (gameList != null && gameList.size() < 20)) {
			isRemove = true;
			notifyDataSetChanged();
		}
		isLoaded = true;
	}

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

	@Override
	public int getItemViewType(int position) {
		if (list.size() == position) {
			return FOOTER_ITEM;
		}
		return position;
	}

	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
		if (i == FOOTER_ITEM){
			View view = LayoutInflater.from(viewGroup.getContext()).inflate(
					R.layout.refresh_footerview, viewGroup, false);
			return new FooterViewHolder(view);
		}
		if (list.get(i).getTest() != null) {
			View view = LayoutInflater.from(viewGroup.getContext()).inflate(
					R.layout.game_test_item, viewGroup, false);
			return new GameTestViewHolder(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, position);
		} else if (viewHolder instanceof GameTestViewHolder) {
			initGameTestViewHolder((GameTestViewHolder) viewHolder, position);
		} else if (viewHolder instanceof FooterViewHolder){
			initFooterViewHolder((FooterViewHolder) viewHolder);
		}
	}

	private void initFooterViewHolder(FooterViewHolder viewHolder) {
		if (isNetworkError) {
			viewHolder.footerview_progressbar.setVisibility(View.GONE);
			viewHolder.footerview_tv_loading.setText("加载失败，点击重试");
			viewHolder.itemView.setClickable(true);
			viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					isNetworkError = false;
					notifyDataSetChanged();
					initList(list.size() / 21);
				}
			});
		} else if (isRemove) {
			viewHolder.footerview_progressbar.setVisibility(View.GONE);
			viewHolder.footerview_tv_loading.setText("加载完毕");
			viewHolder.itemView.setClickable(false);
		} else {
			viewHolder.footerview_progressbar.setVisibility(View.VISIBLE);
			viewHolder.footerview_tv_loading.setText("加载中...");
			viewHolder.itemView.setClickable(false);
		}
	}

	private void initGameTestViewHolder(final GameTestViewHolder holder, 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);
		}

		if (order) {
			holder.home2_game_order.setVisibility(View.VISIBLE);
			holder.home2_game_order.setText(String.valueOf(position + 1));
		} else {
			holder.home2_game_order.setVisibility(View.GONE);
		}

		final GameEntity gameEntity = list.get(position);

		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 {
			holder.gameDes.setText(String.format("%s  %s", gameEntity.getApk().get(0).getSize(), gameEntity.getBrief()));
		}
		holder.gameTestType.setText(gameEntity.getTest().getType());
		if (gameEntity.getTest().getStart() == 0) {
			holder.gameTestTime.setVisibility(View.GONE);
		} else {
			holder.gameTestTime.setText(GameViewUtils.getGameTestDate(gameEntity.getTest().getStart()));
		}

		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, "点击", name, kv);

				Map<String, Object> map = new HashMap<>();
				map.put("location", "列表");
				map.put("page", name);
				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", entrance + "(" + name + ")");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
		});

		if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
			holder.downloadBtn.setVisibility(View.GONE);
		} else {
			if (gameEntity.getTest().getEnd() == 0) {
				holder.downloadBtn.setVisibility(View.VISIBLE);
				DownloadItemUtils.setOnClickListener(context,
						holder.downloadBtn, gameEntity, position,
						SubjectAdapter.this, entrance + "(" + name + ")", name + ":" + gameEntity.getName());
			} else {
				long endTime = Long.valueOf(gameEntity.getTest().getEnd()
						+ "000");
				long todayTime = new Date().getTime();
				if (todayTime > endTime) {
					// 测试时间已过
					holder.downloadBtn.setVisibility(View.GONE);
				} else {
					// 测试时间未过
					holder.downloadBtn.setVisibility(View.VISIBLE);
					DownloadItemUtils.setOnClickListener(context,
							holder.downloadBtn, gameEntity, position,
							SubjectAdapter.this, entrance + "(" + name + ")", name + ":" + gameEntity.getName());
				}
			}
		}

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

	private void initGameNormalViewHolder(final GameNormalViewHolder holder, 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);
		}

		if (order) {
			holder.home1_game_order.setVisibility(View.VISIBLE);
			holder.home1_game_order.setText(String.valueOf(position + 1));
		} else {
			holder.home1_game_order.setVisibility(View.GONE);
		}

		final GameEntity gameEntity = list.get(position);

		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 {
			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, "点击", name, kv);

				Map<String, Object> map = new HashMap<>();
				map.put("location", "列表");
				map.put("page", name);
				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", entrance + "(" + name + ")");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
		});

		DownloadItemUtils.setOnClickListener(context, holder.downloadBtn,
				gameEntity, position, this, entrance + "(" + name + ")", name + ":" + gameEntity.getName());

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

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

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

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

	public boolean isLoaded(){
		return isLoaded;
	}

}
