package com.gh.gamecenter.adapter;

import android.content.Context;
import android.content.Intent;
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.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.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.gamecenter.ConcernActivity;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.ConcernViewHolder;
import com.gh.gamecenter.db.info.ConcernInfo;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.listener.OnCallBackListener;
import com.gh.gamecenter.manager.ConcernManager;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LGT on 2016/9/20.
 */
public class ConcernAdapter extends RecyclerView.Adapter<ConcernViewHolder> {

	private Context context;
	private OnCallBackListener listener;

	private List<ConcernInfo> concernList;
	private List<GameEntity> concernGameList;

	private ConcernManager concernManager;

	public ConcernAdapter(ConcernActivity activity) {
		this.context = activity;
		this.listener = activity;

		concernManager = new ConcernManager(context);

		concernList = concernManager.getConcernGame();
		if (concernList != null && concernList.size() != 0) {
			initConcernGame();
		}
	}

	private int cCount;

	private void addConcernCount() {
		synchronized (ConcernActivity.class) {
			cCount++;
		}
	}

	private void initConcernGame() {
		final List<JSONObject> result = new ArrayList<>();
		final int count = concernList.size();
		cCount = 0;
		for (int i = 0; i < count; i++) {
			JsonObjectExtendedRequest concernObjectRequest = new JsonObjectExtendedRequest(
					TimestampUtils.addTimestamp(
							Config.HOST + "v2d0/game/" + concernList.get(i).getId() + "/digest",
							Constants.GAME_CD),
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							addConcernCount();
							result.add(response);
							if (cCount == count) {
								processingConcernGame(result);
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							addConcernCount();
							if (cCount == count) {
								processingConcernGame(result);
							}
						}
					});
			AppController.addToRequestQueue(concernObjectRequest, ConcernActivity.TAG);
		}
	}

	private void processingConcernGame(List<JSONObject> data) {
		List<GameEntity> gameList = new ArrayList<>();
		Gson gson = new Gson();
		for (int i = 0; i < data.size(); i++) {
			gameList.add(gson.fromJson(data.get(i).toString(), GameEntity.class));
		}
		concernGameList = new ArrayList<>();
		for (int i = 0, sizei = concernList.size(); i < sizei; i++) {
			for (int j = 0, sizej = gameList.size(); j < sizej; j++) {
				if (concernList.get(i).getId().equals(gameList.get(j).getId())) {
					concernGameList.add(gameList.get(j));
					break;
				}
			}
		}
		notifyDataSetChanged();
	}

	@Override
	public ConcernViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		View view = LayoutInflater.from(parent.getContext()).inflate(
				R.layout.concern_item, parent, false);
		return new ConcernViewHolder(view);
	}

	@Override
	public void onBindViewHolder(final ConcernViewHolder holder, int position) {
		ConcernInfo concernInfo = concernList.get(position);
		ImageUtils.getInstance(context).display(concernInfo.getIcon(), holder.concern_item_icon);
		holder.concern_item_name.setText(concernInfo.getGameName());
		holder.concern_item_concern.setText("取消关注");
		holder.concern_item_concern.setBackgroundResource(R.drawable.textview_cancel_style);
		holder.concern_item_concern.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 删除关注表中的数据，并更新界面
				DialogUtils.showCancelDialog(context, new DialogUtils.ConfiremListener() {
					@Override
					public void onConfirem() {
						ConcernInfo concernInfo = concernList.get(holder.getPosition());
						if (concernManager.findConcernById(concernInfo.getId()) != null) {
							concernList.remove(holder.getPosition());

							Map<String, Object> kv = new HashMap<>();
							kv.put("状态", "取消关注");
							DataUtils.onEvent(context, "游戏关注", concernInfo.getGameName(), kv);

							Map<String, Object> map = new HashMap<>();
							map.put("game", concernInfo.getGameName());
							map.put("game_id", concernInfo.getId());
							map.put("type", "取消关注");
							DataCollectionManager.onEvent(context, "concern", map);

							concernManager.deleteConcern(concernInfo.getId());
							if (concernGameList != null) {
								concernGameList.remove(holder.getPosition());
							}
//							notifyItemRemoved(holder.getPosition());
							notifyDataSetChanged();
							if (concernList.isEmpty()) {
								listener.loadEmpty();
							}
							holder.concern_item_concern.setClickable(false);
							holder.itemView.setClickable(false);
						} else {
							Toast.makeText(context, "取消失败，请稍后再试", Toast.LENGTH_SHORT).show();
						}
					}
				});
			}
		});
		holder.itemView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (concernGameList != null && concernGameList.size() != 0) {
					GameEntity gameEntity = concernGameList.get(holder.getPosition());

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

	@Override
	public int getItemCount() {
		if (concernList == null) {
			return 0;
		}
		return concernList.size();
	}

	public List<GameEntity> getConcernGameList() {
		if (concernGameList == null) {
			concernGameList = new ArrayList<>();
		}
		return concernGameList;
	}

	public List<ConcernInfo> getConcernList() {
		if (concernList == null) {
			concernList = new ArrayList<>();
		}
		return concernList;
	}
}
