package com.gh.gamecenter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.CardView;
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.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.base.BaseActivity;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.MeasureHeightLayoutManager;
import com.gh.common.util.NewsUtils;
import com.gh.common.view.VerticalItemDecoration;
import com.gh.gamecenter.adapter.viewholder.FooterViewHolder;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by khy on 2016/8/22.
 */
public class NewsSearchActivity extends BaseActivity {

    public static final String TAG = NewsSearchActivity.class.getSimpleName();

    private RecyclerView gamedetail_news_rv;
    private List<NewsEntity> newsEntities;
    private NewsSearchAdapter searchAdapter;
    private TextView tv_search;
    private LinearLayout reuse_none_data;
    private EditText et_search;
    private LinearLayout gamedetail_news_ll_loading;
    private LinearLayout reuse_no_connection;
    private CardView gamedetail_news_cardView;

    private MeasureHeightLayoutManager layoutManager;

    private boolean isLoadOver = true;
    private boolean isRemove = false;
    private boolean isNetworkError = false;

    private String gameName;
    private String searchKey;
    private String gameId;
    private String entrance;

    private Handler handler = new Handler();

    private int page = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        gameName = intent.getExtras().getString("gameName");
        searchKey = intent.getExtras().getString("searchKey");
        gameId = intent.getExtras().getString("gameId");
        entrance = intent.getExtras().getString("entrance");

        View view = View.inflate(this, R.layout.activity_gamedetail_news, null);
        init(view, gameName);

        newsEntities = new ArrayList<>();
        searchAdapter = new NewsSearchAdapter();

        findViewById(R.id.gamedetail_news_type_ll).setVisibility(View.GONE);
        findViewById(R.id.ll_search).setVisibility(View.VISIBLE);

        layoutManager = new MeasureHeightLayoutManager(this);

        gamedetail_news_rv.setLayoutManager(layoutManager);
        gamedetail_news_rv.setAdapter(searchAdapter);
        gamedetail_news_rv.addItemDecoration(new VerticalItemDecoration(NewsSearchActivity.this, 1));

        et_search.setText(searchKey);

        new Thread(new Runnable() {
            @Override
            public void run() {
                loadNewsData(page);
            }
        }).start();

        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchKey = et_search.getText().toString().trim();
                if (searchKey.length() >= 1) {
                    newsEntities.clear();
                    searchAdapter.notifyDataSetChanged();
                    gamedetail_news_ll_loading.setVisibility(View.VISIBLE);
                    reuse_none_data.setVisibility(View.GONE);
                    gamedetail_news_cardView.setVisibility(View.GONE);
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            page = 1;
                            loadNewsData(page);
                        }
                    },1000);

                }else {
                    Toast.makeText(getApplicationContext(),"请输入关键字",Toast.LENGTH_SHORT).show();
                }

            }
        });

        gamedetail_news_rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&layoutManager.findLastVisibleItemPosition() + 1 == searchAdapter.getItemCount()
                        &&isLoadOver&&!isRemove&& !isNetworkError){
                    isLoadOver = false;
                    page++;
                    loadNewsData(page);
                }
            }
        });

        reuse_no_connection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reuse_no_connection.setVisibility(View.GONE);
                gamedetail_news_ll_loading.setVisibility(View.VISIBLE);
                gamedetail_news_cardView.setVisibility(View.GONE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadNewsData(1);
                    }
                },1000);
            }
        });

    }

    private void loadNewsData(final int page) {
        DataUtils.onEvent(this, "游戏新闻搜索", searchKey);

        Map<String, Object> map = new HashMap<>();
        map.put("key", searchKey);
        map.put("from", "游戏新闻搜索");
        DataCollectionManager.onEvent(this, "search", map);

        String url = Config.HOST + "v1d45/search/news?game_id=" + gameId
                + "&keyword=" + Uri.encode(searchKey) + "&page="+ page + "&limit=20";
        final JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Gson gson = new Gson();
                        ArrayList<NewsEntity> news = gson.fromJson(
                                response.toString(),
                                new TypeToken<ArrayList<NewsEntity>>() {
                                }.getType());
                        newsEntities.addAll(news);
                        searchAdapter.notifyDataSetChanged();
                        isLoadOver = true;
                        gamedetail_news_ll_loading.setVisibility(View.GONE);
                        gamedetail_news_cardView.setVisibility(View.VISIBLE);
                        if (newsEntities.size() == 0){
                            gamedetail_news_cardView.setVisibility(View.GONE);
                            reuse_none_data.setVisibility(View.VISIBLE);
                        }else {
                            gamedetail_news_cardView.setVisibility(View.VISIBLE);
                            reuse_none_data.setVisibility(View.GONE);
                        }
                        if (news.isEmpty() || (news.size() < 20)) {
                            isRemove = true;
                            searchAdapter.notifyItemChanged(searchAdapter.getItemCount() - 1);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (page ==1){
                            reuse_no_connection.setVisibility(View.VISIBLE);
                            gamedetail_news_ll_loading.setVisibility(View.GONE);
                        }
                        isLoadOver = true;
                        toast("加载失败，请检查网络状态");
                        isNetworkError = true;
                        searchAdapter.notifyItemChanged(searchAdapter.getItemCount() - 1);
                    }
                });
        AppController.addToRequestQueue(request, TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppController.canclePendingRequests(TAG);
        gameName = null;
        searchKey = null;
        gameId = null;
        gamedetail_news_rv = null;
        newsEntities = null;
        searchAdapter = null;
        tv_search = null;
        reuse_none_data = null;
        et_search = null;
        gamedetail_news_ll_loading = null;
        reuse_no_connection = null;
        gamedetail_news_cardView = null;
        layoutManager = null;
        handler = null;
    }

    public class NewsSearchAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        @Override
        public int getItemViewType(int position) {
            if (position == newsEntities.size()) {
                return 0;
            }else {
                return 1;
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 0){
                View view = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.refresh_footerview, parent, false);
                return new FooterViewHolder(view);
            }else {
                LinearLayout linearLayout = new LinearLayout(getApplicationContext());
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                linearLayout.setBackgroundResource(R.drawable.cardview_item_style);

                TextView textView = new TextView(getApplicationContext());
                textView.setPadding(DisplayUtils.dip2px(NewsSearchActivity.this,10),DisplayUtils.dip2px(NewsSearchActivity.this,10)
                        ,0, DisplayUtils.dip2px(NewsSearchActivity.this,10));
                textView.setTextColor(Color.parseColor("#3a3a3a"));
                textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                textView.setSingleLine();
                textView.setTextSize(15);

                linearLayout.addView(textView);

                return new ViewHolder(linearLayout);
            }
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof ViewHolder){
                ViewHolder viewHolder = (ViewHolder) holder;
                viewHolder.tvTitle.setText(newsEntities.get(position).getTitle());
                viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        NewsEntity newsEntity = newsEntities.get(holder.getPosition());

                        Map<String, Object> kv = new HashMap<>();
                        kv.put("名字", newsEntity.getTitle());
                        kv.put("位置", String.valueOf(holder.getPosition() + 1));
                        DataUtils.onEvent(NewsSearchActivity.this, "点击", "游戏新闻搜索", 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(NewsSearchActivity.this, "click-item", map);

                        // 统计阅读量
                        NewsUtils.statNewsViews(newsEntity.getId());
                        NewsUtils.startNewsActivity(NewsSearchActivity.this, newsEntity, entrance + "+(游戏新闻搜索)");
                    }
                });
            }else if (holder instanceof FooterViewHolder){
                FooterViewHolder viewHolder = (FooterViewHolder) holder;
                viewHolder.itemView.setPadding(0, 0, 0, 0);
                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;
                            notifyItemChanged(getItemCount() - 1);
                            loadNewsData(page);
                        }
                    });
                } 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);
                }
            }

        }

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

        public class ViewHolder extends RecyclerView.ViewHolder{
            LinearLayout linearLayout;
            TextView tvTitle;
            public ViewHolder(View itemView) {
                super(itemView);
                linearLayout = (LinearLayout) itemView;
                tvTitle = (TextView) linearLayout.getChildAt(0);
            }
        }
    }
}
