package com.gh.gamecenter.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
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.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.view.CardLinearLayout;
import com.gh.gamecenter.GameNewsActivity;
import com.gh.gamecenter.NewsSearchActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.GameNewsSearchViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNewsTypeListViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsFooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsTextViewHolder;
import com.gh.gamecenter.entity.NewsEntity;
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;

/**
 * Created by LGT on 2016/8/29.
 */
public class GameNewsAdapter extends RecyclerView.Adapter {

	private Context context;
	private RecyclerView game_news_list;

	private ArrayList<NewsEntity> newsList;
	private ArrayList<String> typeList;

	private String gameId;
	private String newsType;
	private String entrance;

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

	public GameNewsAdapter(Context context,
	                       ArrayList<String> tList,
	                       RecyclerView game_news_list,
	                       String id,
	                       String type,
	                       String entrance) {
		this.context = context;

		this.game_news_list = game_news_list;

		newsList = new ArrayList<>();
		typeList = tList;

		gameId = id;
		newsType = type;
		this.entrance = entrance;

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

		addList(0);
	}

	public void addList(final int offset) {
		if (isLoading) {
			return;
		}
		isLoading = true;

		String url;
		if ("全部".equals(newsType)) {
			url = Config.HOST + "v1d45/game/" + gameId + "/news?limit=20&offset=" + offset;
		} else {
			url = Config.HOST + "v1d45/game/" + gameId + "/news?limit=20&offset="
					+ offset + "&type=" + Uri.encode(newsType);
		}

		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url,
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						Type listType = new TypeToken<ArrayList<NewsEntity>>() {}.getType();
						Gson gson = new Gson();
						List<NewsEntity> list = gson.fromJson(response.toString(), listType);
						if (offset == 0){
							newsList.clear();
						}
						if (list != null) {
							newsList.addAll(list);
							if (offset == 0) {
								game_news_list.scrollToPosition(1);
							}
							notifyItemChanged(getItemCount() - list.size() - 2);
							notifyItemRangeInserted(newsList.size() - list.size() + 2, list.size());

							if (list.size() < 20) {
								isRemove = true;
								notifyItemChanged(getItemCount() - 1);
							}
						}

						isLoading = false;
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						isLoading = false;
						isNetworkError = true;
					}
				});
		AppController.addToRequestQueue(request, GameNewsActivity.TAG);
	}

	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		if (viewType == 0) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.game_news_search_item, parent, false);
			return new GameNewsSearchViewHolder(view);
		} else if (viewType == 1) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.game_news_type_item, parent, false);
			return new GameNewsTypeListViewHolder(view);
		} else if (newsList.size() > 0 && viewType > 1 && viewType <= 1 + newsList.size()) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.home_list_item_newsnormal_type, parent, false);
			return new NewsTextViewHolder(view);
		} else {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.gamedetail_item_loading, parent, false);
			return new NewsFooterViewHolder(view);
		}
	}

	@Override
	public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
		if (holder instanceof GameNewsTypeListViewHolder) {
			GameNewsTypeListViewHolder viewHolder = (GameNewsTypeListViewHolder) holder;
			ViewGroup.LayoutParams params = viewHolder.game_news_type_list.getLayoutParams();
			params.height = (int) Math.ceil(typeList.size() / 5f) * DisplayUtils.dip2px(context, 35) + DisplayUtils.dip2px(context, 12);
			viewHolder.game_news_type_list.setLayoutParams(params);

			if (viewHolder.game_news_type_list.getAdapter() == null) {
				viewHolder.game_news_type_list.setHasFixedSize(true);
				viewHolder.game_news_type_list.setLayoutManager(new GridLayoutManager(context, 5));
				viewHolder.game_news_type_list.setAdapter(new GameNewsTypeListAdapter(typeList, newsType));
			}
		} else if (holder instanceof NewsTextViewHolder) {
			final NewsTextViewHolder viewHolder = (NewsTextViewHolder) holder;

			viewHolder.newsType.setVisibility(View.GONE);

			// 第一个
			if (position - 2 == 0) {
				viewHolder.news_line.setVisibility(View.GONE);
//				((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
			} else {
				viewHolder.news_line.setVisibility(View.VISIBLE);
				((CardLinearLayout) holder.itemView).setmTop(0);
			}

			// 最后一个
			if (position - 1 == newsList.size()) {
				((CardLinearLayout) viewHolder.itemView).setBottom(true);
				((CardLinearLayout) viewHolder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
			} else {
				((CardLinearLayout) viewHolder.itemView).setBottom(false);
				((CardLinearLayout) viewHolder.itemView).setmBottom(0);
			}

			final NewsEntity newsEntity = newsList.get(position - 2);
			viewHolder.newsType.setBackgroundResource(NewsUtils.getDrawableIdByType(newsEntity.getType()));
			viewHolder.newsType.setText(newsEntity.getType());
			viewHolder.newsTitle.setText(newsEntity.getTitle());
			viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Map<String, Object> kv = new HashMap<>();
					kv.put("名字", newsEntity.getTitle());
					kv.put("位置", String.valueOf(viewHolder.getPosition() + 1));
					DataUtils.onEvent(context, "点击", "游戏新闻详情", kv);

					Map<String, Object> map = new HashMap<>();
					map.put("location", newsType);
					map.put("page", "游戏新闻详情");
					map.put("news", newsEntity.getTitle());
					map.put("news_id", newsEntity.getId());
					DataCollectionManager.onEvent(context, "click-item", map);

					// 统计阅读量
					NewsUtils.statNewsViews(newsEntity.getId());
					NewsUtils.startNewsActivity(context, newsEntity, entrance + "+(游戏新闻详情:" + newsType + ")");
				}
			});
		} else if (holder instanceof NewsFooterViewHolder){
			NewsFooterViewHolder footerViewHolder = ((NewsFooterViewHolder) holder);
			if (isRemove){
				footerViewHolder.item_tv_loading.setText("加载完毕");
				footerViewHolder.item_pb_loading.setVisibility(View.GONE);
			}else {
				footerViewHolder.item_tv_loading.setText("加载中...");
				footerViewHolder.item_pb_loading.setVisibility(View.VISIBLE);
			}
		} else if (holder instanceof GameNewsSearchViewHolder){
			if (isOpenKeyBoard){
				((GameNewsSearchViewHolder) holder).game_news_et_search.requestFocus();
				InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
				isOpenKeyBoard = false;
			}

			GameNewsSearchViewHolder searchViewHolder = ((GameNewsSearchViewHolder) holder);
			searchViewHolder.game_news_tv_search.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String searchKey = ((GameNewsSearchViewHolder) holder).game_news_et_search.getText().toString().trim();
					if (searchKey.length() >= 1) {
						Intent intent = new Intent(context,NewsSearchActivity.class);
						intent.putExtra("gameName", "搜索结果");
						intent.putExtra("searchKey", searchKey);
						intent.putExtra("gameId", gameId);
						intent.putExtra("entrance", entrance + "+(游戏新闻详情:" + newsType + ")");
						context.startActivity(intent);
					}else {
						Toast.makeText(context,"请输入关键字",Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
	}

	@Override
	public int getItemCount() {
		return 3 + newsList.size();
	}

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

	public ArrayList<NewsEntity> getNewsList() {
		return newsList;
	}

	public boolean isLoading() {
		return isLoading;
	}

	public boolean isRemove() {
		return isRemove;
	}

	public boolean isNetworkError() {
		return isNetworkError;
	}

	public void openKeyBoard() {
		isOpenKeyBoard = true;
		notifyItemChanged(0);
	}

}
