package com.gh.gamecenter.news;

import android.content.Context;
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.widget.TextView;
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.ImageUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.view.CardLinearLayout;
import com.gh.common.view.CardRelativeLayout;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.NewsFooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsHeadViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsImageViewHolder;
import com.gh.gamecenter.adapter.viewholder.NewsTextViewHolder;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.listener.OnCallBackListener;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 *
 * @author 温冠超
 * @email 294299195@qq.com
 * @date 2015-8-5 modified 2015-8-21 资讯首页模块
 */
public class News3FragmentAdapter extends
		RecyclerView.Adapter<RecyclerView.ViewHolder> {

	public static class ITEM_TYPE {
		public static final int head = 1;// head
		public static final int news_text = 2;// 新闻列表1类型
		public static final int news_image = 3;// 新闻列表2类型
		public static final int refresh_footer = 4;// 刷新布局类型
	}

	private int position_today = -1;// 今天head的位置
	private int position_before = -1;// 昨天/以前head的位置

	private Context context;
	private OnCallBackListener listener;

	private TextView news_tv_label;

	private List<NewsEntity> todayNewsList;
	private List<NewsEntity> beforeNewsList;

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

	public News3FragmentAdapter(News3Fragment fregment,
	                            TextView tlabel,
	                            boolean isLoad) {

		this.context = fregment.getActivity();
		this.listener = fregment;

		news_tv_label = tlabel;

		todayNewsList = new ArrayList<>();
		beforeNewsList = new ArrayList<>();

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

		if (isLoad) {
			load();
		}
	}

	public void load() {
		addList(0);
	}

	public void addList(final int offset) {
		if (isLoading) {
			return;
		}
		isLoading = true;
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
				TimestampUtils.addTimestamp(
						Config.HOST + "v1d45/news?type_group=" + Uri.encode("攻略")
								+ "&offset=" + offset + "&limit=20",
						Constants.NEWS_CD),
				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);

						//去重
						list = removeDuplicate(list);

						SimpleDateFormat format = new SimpleDateFormat("Mdd", Locale.getDefault());
						int today = Integer.valueOf(format.format(new Date()));

						if (offset == 0) {
							for (int i = 0, size = list.size(); i < size; i++) {
								int day = Integer.valueOf(format.format(new Date(
										Long.valueOf(list.get(i).getPublishOn() + "000"))));
								if (day == today) {
									todayNewsList.add(list.get(i));
								} else {
									beforeNewsList.add(list.get(i));
								}
							}

							refreshCount();
						} else {
							for (int i = 0, size = list.size(); i < size; i++) {
								int day = Integer.valueOf(format.format(new Date(Long.valueOf(list
										.get(i).getPublishOn() + "000"))));
								if (day == today) {
									todayNewsList.add(list.get(i));
									if (todayNewsList.size() == 1) {
										position_today = 0;
										notifyItemRangeInserted(0, 2);
									} else {
										notifyItemInserted(todayNewsList.size());
									}
								} else {
									beforeNewsList.add(list.get(i));
									if (beforeNewsList.size() == 1 && position_before == -1) {
										if (position_today == -1) {
											position_before = 0;
											notifyItemRangeInserted(0, 2);
										} else if (position_today == -1) {
											position_before = todayNewsList.size() + 1;
											notifyItemRangeChanged(position_before, 2);
										}
									} else {
										notifyItemInserted(getItemCount() - 2);
									}
								}
							}
							notifyItemChanged(getItemCount() - list.size() - 2);
						}

						listener.loadDone();

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

						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, News3Fragment.TAG);
	}

	//去除重复数据
	private List<NewsEntity> removeDuplicate(List<NewsEntity> list) {
		for (int i = 0; i < list.size(); i++) {
			String id = list.get(i).getId();
			final int index = i;

			if (!todayNewsList.isEmpty()) {
				for (int j = 0; j < todayNewsList.size(); j++) {
					if (id.equals(todayNewsList.get(j).getId())) {
						list.remove(i);
						i--;
						break;
					}
				}
				if (index != i) {
					continue;
				}
			}

			if (!beforeNewsList.isEmpty()) {
				for (int j = 0; j < beforeNewsList.size(); j++) {
					if (id.equals(beforeNewsList.get(j).getId())) {
						list.remove(i);
						i--;
						break;
					}
				}
			}
		}
		return list;
	}

	private void refreshCount() {

		position_today = -1;
		position_before = -1;

		if (!todayNewsList.isEmpty()) {
			position_today = 0;
		}

		if (!beforeNewsList.isEmpty()) {
			if (position_today != -1) {
				position_before = todayNewsList.size() + 1;
			} else if (position_today == -1) {
				position_before = 0;
			}
		}

		if (position_today != -1) {
			news_tv_label.setText("今天");
			news_tv_label.setTextColor(0xFF00B7FA);
		} else if (position_before != -1) {
			news_tv_label.setText("昨天/以前");
			news_tv_label.setTextColor(0xFF3A3A3A);
		}

		notifyDataSetChanged();
	}

	@Override
	public int getItemCount() {
		int head = 0;
		if (position_today != -1) {
			head++;
		}
		if (position_before != -1) {
			head++;
		}
		if (head == 0) {
			return 0;
		}
		return head + todayNewsList.size() + beforeNewsList.size() + 1;
	}

	@Override
	public int getItemViewType(int position) {

		if (position_today != -1) {
			if (position == position_today) {
				return ITEM_TYPE.head;
			}
			if (position == position_today + 1) {
				if (!TextUtils.isEmpty(todayNewsList.get(0).getThumb())) {
					return ITEM_TYPE.news_image;
				} else {
					return ITEM_TYPE.news_text;
				}
			}
			if (position > position_today + 1
					&& position <= todayNewsList.size() + position_today) {
				return ITEM_TYPE.news_text;
			}
		}

		if (position_before != -1) {
			if (position == position_before) {
				return ITEM_TYPE.head;
			}
			if (position > position_before
					&& position <= beforeNewsList.size() + position_before) {
				return ITEM_TYPE.news_text;
			}
		}

		return ITEM_TYPE.refresh_footer;
	}

	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		if (viewType == ITEM_TYPE.head) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.news_list_item_category, parent, false);
			return new NewsHeadViewHolder(view);
		} else if (viewType == ITEM_TYPE.news_image) {
			View view = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.home_list_item_newsimage_type, parent, false);
			return new NewsImageViewHolder(view);
		} else if (viewType == ITEM_TYPE.news_text) {
			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(RecyclerView.ViewHolder holder, int position) {
		if (holder instanceof NewsHeadViewHolder) {
			NewsHeadViewHolder viewHolder = (NewsHeadViewHolder) holder;

			if (position == position_today) {
				CardRelativeLayout cardRelativeLayout = (CardRelativeLayout) viewHolder.itemView;
				cardRelativeLayout.setmBottom(DisplayUtils.dip2px(context, 8));
				viewHolder.headType.setText("今天");
				viewHolder.headType.setTextColor(0xFF1BA4FC);
			}

			if (position == position_before) {
				CardRelativeLayout cardRelativeLayout = (CardRelativeLayout) viewHolder.itemView;
//				if (position_today == -1) {
					cardRelativeLayout.setmTop(0);
//				} else {
//					cardRelativeLayout.setmTop(DisplayUtils.dip2px(context, 8));
//				}
				cardRelativeLayout.setmBottom(DisplayUtils.dip2px(context, 8));
				viewHolder.headType.setText("昨天/以前");
				viewHolder.headType.setTextColor(0xFF3A3A3A);
			}
		} else if (holder instanceof NewsImageViewHolder) {
			NewsImageViewHolder viewHolder = (NewsImageViewHolder) holder;

			final NewsEntity newsEntity = todayNewsList.get(0);
			ImageUtils.getInstance(context).display(newsEntity.getThumb(), viewHolder.newsThumb);
			String title = newsEntity.getTitle();
			if (title.contains("》")) {
				viewHolder.newsMainTitle.setText(title.substring(0, title.indexOf("》") + 1));
				viewHolder.newsSubTitle.setVisibility(View.VISIBLE);
				viewHolder.newsSubTitle.setText(title.substring(title.indexOf("》") + 1));
			} else if (title.contains(" ")) {
				viewHolder.newsMainTitle.setText(title.substring(0, title.indexOf(" ") + 1));
				viewHolder.newsSubTitle.setVisibility(View.VISIBLE);
				viewHolder.newsSubTitle.setText(title.substring(title.indexOf(" ") + 1));
			} else {
				viewHolder.newsMainTitle.setText(title);
				viewHolder.newsSubTitle.setVisibility(View.GONE);
			}
			viewHolder.itemView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Map<String, Object> kv = new HashMap<>();
					kv.put("名字", newsEntity.getTitle());
					kv.put("位置", "今天-大图");
					DataUtils.onEvent(context, "点击", "资讯-攻略", kv);

					Map<String, Object> map = new HashMap<>();
					map.put("location", "今天-大图");
					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, "(资讯-攻略:今天)");
				}
			});
		} else if (holder instanceof NewsTextViewHolder) {
			NewsTextViewHolder viewHolder = (NewsTextViewHolder) holder;

			NewsEntity newsEntity = null;
			String from = null;
			if (position > position_today
					&& position <= todayNewsList.size() + position_today) {
				newsEntity = todayNewsList.get(position - position_today - 1);
				from = "今天";
				// 第一个
				if (position - position_today - 1 == 0) {
					((CardLinearLayout) viewHolder.itemView).setmTop(0);
					viewHolder.news_line.setVisibility(View.GONE);
				} else {
					((CardLinearLayout) viewHolder.itemView).setmTop(0);
					viewHolder.news_line.setVisibility(View.VISIBLE);
				}

				// 最后一个
				if (position - position_today == todayNewsList.size()) {
					((CardLinearLayout) viewHolder.itemView).setBottom(true);
					((CardLinearLayout) viewHolder.itemView).setmBottom(0);
				} else {
					((CardLinearLayout) viewHolder.itemView).setBottom(false);
					((CardLinearLayout) viewHolder.itemView).setmBottom(0);
				}
			} else if (position > position_before
					&& position <= beforeNewsList.size() + position_before) {
				newsEntity = beforeNewsList.get(position - position_before - 1);
				from = "昨天/以前";
				// 第一个
				if (position - position_before - 1 == 0) {
					((CardLinearLayout) viewHolder.itemView).setmTop(0);
					viewHolder.news_line.setVisibility(View.GONE);
				} else {
					((CardLinearLayout) viewHolder.itemView).setmTop(0);
					viewHolder.news_line.setVisibility(View.VISIBLE);
				}

				// 最后一个
				if (position - position_before == beforeNewsList.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);
				}
			}
			if (newsEntity != null) {
				final NewsEntity entity = newsEntity;
				final String entrance = from;
				viewHolder.newsType.setBackgroundResource(NewsUtils
						.getDrawableIdByType(entity.getType()));
				viewHolder.newsType.setText(entity.getType());
				viewHolder.newsTitle.setText(entity.getTitle());
				viewHolder.itemView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Map<String, Object> kv = new HashMap<>();
						kv.put("名字", entity.getTitle());
						kv.put("位置", entrance);
						DataUtils.onEvent(context, "点击", "资讯-攻略", kv);

						Map<String, Object> map = new HashMap<>();
						map.put("location", entrance);
						map.put("page", "资讯-攻略");
						map.put("news", entity.getTitle());
						map.put("news_id", entity.getId());
						DataCollectionManager.onEvent(context, "click-item", map);

						//统计阅读量
						NewsUtils.statNewsViews(entity.getId());
						NewsUtils.startNewsActivity(context, entity, "(资讯-攻略:" + entrance + ")");
					}
				});
			}
		} else if (holder instanceof NewsFooterViewHolder) {
			NewsFooterViewHolder viewHolder = (NewsFooterViewHolder) holder;

			if (isNetworkError) {
				viewHolder.item_pb_loading.setVisibility(View.GONE);
				viewHolder.item_tv_loading.setText("加载失败，点击重试");
				viewHolder.itemView.setClickable(true);
				viewHolder.itemView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						isNetworkError = false;
						notifyItemChanged(getItemCount() - 1);
						addList(getAllListSize());
					}
				});
			} else if (isRemove) {
				viewHolder.item_pb_loading.setVisibility(View.GONE);
				viewHolder.item_tv_loading.setText("加载完毕");
				viewHolder.itemView.setClickable(false);
			} else {
				viewHolder.item_pb_loading.setVisibility(View.VISIBLE);
				viewHolder.item_tv_loading.setText("加载中...");
				viewHolder.itemView.setClickable(false);
			}
		}
	}

	public int getAllListSize() {
		return todayNewsList.size() + beforeNewsList.size();
	}

	public int getTodaySize() {
		return todayNewsList.size();
	}

	public int getPosition_today() {
		return position_today;
	}

	public int getPosition_before() {
		return position_before;
	}

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