package com.gh.gamecenter.search;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

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.DisplayUtils;
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.common.view.DownloadDialog;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.GameNormalViewHolder;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.manager.DataCollectionManager;
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;

public class SearchGameDetailFragmentAdapter extends RecyclerView.Adapter<GameNormalViewHolder> {

	private Context context;

	private RecyclerView search_detail;
	private LinearLayout search_loading;
	private LinearLayout search_nogame;
	private LinearLayout search_connection;

	private List<GameEntity> gameList;

	private String key;

	public SearchGameDetailFragmentAdapter(Context context,
	                                       RecyclerView search_detail,
	                                       LinearLayout search_loading,
	                                       LinearLayout search_nogame,
	                                       LinearLayout search_connection,
	                                       String key) {

		this.context = context;
		this.search_detail = search_detail;
		this.search_loading = search_loading;
		this.search_nogame = search_nogame;
		this.search_connection = search_connection;

		gameList = new ArrayList<>();

		this.key = key;
		if (!TextUtils.isEmpty(key)) {
			search_loading.setVisibility(View.VISIBLE);
			search_detail.setVisibility(View.GONE);
			search_nogame.setVisibility(View.GONE);
			search_connection.setVisibility(View.GONE);
			search(key);
		} else {
			search_loading.setVisibility(View.GONE);
			search_detail.setVisibility(View.GONE);
			search_nogame.setVisibility(View.VISIBLE);
			search_connection.setVisibility(View.GONE);
		}
	}

	private void search(String key) {
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
				TimestampUtils.addTimestamp(
						Config.HOST + "v1d45/search/game?keyword=" + Uri.encode(key),
						Constants.SEARCH_CD),
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						search_loading.setVisibility(View.GONE);

						Type listType = new TypeToken<ArrayList<GameEntity>>() {}.getType();
						Gson gson = new Gson();
						List<GameEntity> list = gson.fromJson(response.toString(), listType);
						if (list != null && list.size() > 0) {
							search_detail.setVisibility(View.VISIBLE);
							gameList.addAll(list);
							notifyItemRangeInserted(gameList.size() - list.size(), list.size());
						} else {
							search_nogame.setVisibility(View.VISIBLE);
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						search_loading.setVisibility(View.GONE);
						search_connection.setVisibility(View.VISIBLE);
					}
				});
		AppController.addToRequestQueue(request, SearchGameDetailFragment.TAG);
	}

	@Override
	public int getItemCount() {
		return gameList.size();
	}

	@Override
	public GameNormalViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
		View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(
				R.layout.game_normal_item, viewGroup, false);
		return new GameNormalViewHolder(itemView);
	}

	@Override
	public void onBindViewHolder(final GameNormalViewHolder viewHolder, int position) {
		final GameEntity gameEntity = gameList.get(position);

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

		// 最后一个
		if (position + 1 == gameList.size()) {
			((CardLinearLayout) viewHolder.itemView).setBottom(true);
		} else {
			((CardLinearLayout) viewHolder.itemView).setBottom(false);
		}

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

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

		viewHolder.itemView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DataUtils.onEvent(context, "搜索页面", key);

				Map<String, Object> map = new HashMap<>();
				map.put("key", key);
				map.put("from", "搜索页面");
				map.put("click", gameEntity.getName());
				DataCollectionManager.onEvent(context, "search", map);

				Map<String, Object> kv = new HashMap<>();
				kv.put("名字", gameEntity.getName());
				kv.put("位置", String.valueOf(viewHolder.getPosition() + 1));
				DataUtils.onEvent(context, "点击", "搜索", kv);

				Map<String, Object> map2 = new HashMap<>();
				map2.put("location", "列表");
				map2.put("page", "搜索");
				map2.put("game", gameEntity.getName());
				map2.put("game_id", gameEntity.getId());
				DataCollectionManager.onEvent(context, "click-item", map2);

				AppController.put("GameEntity", gameEntity);
				Intent intent = new Intent(context, GameDetailActivity.class);
				intent.putExtra("entrance", "(搜索)");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
		});

		if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
			viewHolder.downloadBtn.setVisibility(View.GONE);
		} else {
			viewHolder.downloadBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(final View v) {
					InputMethodManager imm = (InputMethodManager) context
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					DataUtils.onEvent(context, "搜索页面", key);

					Map<String, Object> map = new HashMap<>();
					map.put("key", key);
					map.put("from", "搜索页面");
					map.put("click", gameEntity.getName());
					DataCollectionManager.onEvent(context, "search", map);

					DownloadDialog.getInstance(context)
							.showPopupWindow(v, gameEntity, "(搜索)", "搜索:" + gameEntity.getName());
				}
			});
		}

		if (Config.isShow(context)) {
			viewHolder.downloadBtn.setVisibility(View.VISIBLE);
		} else {
			viewHolder.downloadBtn.setVisibility(View.GONE);
		}
	}

}
