package com.gh.gamecenter.news;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gc.materialdesign.views.ProgressBarCircularIndeterminate;
import com.gh.base.AppController;
import com.gh.base.BaseFragment;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBNetworkState;
import com.gh.gamecenter.eventbus.EBUISwitch;

/**
 * Created by khy on 2016/6/29.
 */
public class News3Fragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

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

    private SwipeRefreshLayout news_swipe_refresh;
    private RecyclerView news_rv_list;
    private LinearLayoutManager layoutManager;
    private News3FragmentAdapter adapter;
    private ProgressBarCircularIndeterminate news_pb_loading;
    private LinearLayout reuse_no_connection;
    private TextView news_tv_label;
    private RelativeLayout news_rl_label;
    private RelativeLayout.LayoutParams rparams;

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

        init(R.layout.fragment_news3);

        news_swipe_refresh.setColorSchemeResources(R.color.theme);
        news_swipe_refresh.setOnRefreshListener(this);

        reuse_no_connection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                news_rv_list.setVisibility(View.VISIBLE);
                news_pb_loading.setVisibility(View.GONE);
                reuse_no_connection.setVisibility(View.GONE);
                adapter = new News3FragmentAdapter(News3Fragment.this, news_tv_label, true);
                news_rv_list.setAdapter(adapter);
            }
        });

        rparams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        news_rv_list.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager( getActivity());
        news_rv_list.setLayoutManager(layoutManager);
        adapter = new News3FragmentAdapter(this, news_tv_label, false);
        news_rv_list.setAdapter(adapter);
        news_rv_list.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int position = layoutManager.findFirstVisibleItemPosition();

                if (position == 0
                        && layoutManager.findViewByPosition(position).getTop() == 0) {
                    news_rl_label.setVisibility(View.GONE);
                } else {
                    if (!news_swipe_refresh.isRefreshing()) {
                        news_rl_label.setVisibility(View.VISIBLE);
                    }
                }

                if (adapter.getPosition_today() != -1
                        && position >= adapter.getPosition_today()
                        && position <= adapter.getTodaySize()
                        + adapter.getPosition_today()) {
                    news_tv_label.setText("今天");
                    news_tv_label.setTextColor(0xFF00B7FA);
                } else if (adapter.getPosition_before() != -1
                        && position >= adapter.getPosition_before()) {
                    news_tv_label.setText("昨天/以前");
                    news_tv_label.setTextColor(0xFF3A3A3A);
                }

                if (position == adapter.getPosition_today() - 1
                        || position == adapter.getPosition_before() - 1) {
                    int buttom = layoutManager.findViewByPosition(position).getBottom();
                    if (buttom <= news_rl_label.getHeight()) {
                        rparams.topMargin = buttom - news_rl_label.getHeight();
                        news_rl_label.setLayoutParams(rparams);
                    } else {
                        rparams.topMargin = 0;
                        news_rl_label.setLayoutParams(rparams);
                    }
                } else {
                    rparams.topMargin = 0;
                    news_rl_label.setLayoutParams(rparams);
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!isDestroy && newState == RecyclerView.SCROLL_STATE_IDLE
                        && layoutManager.findLastVisibleItemPosition() + 1 == adapter.getItemCount()) {
                    if (!adapter.isRemove() && !adapter.isLoading() && !adapter.isNetworkError()) {
                        adapter.addList(adapter.getAllListSize());
                    }
                }
            }
        });
    }

    @Override
    public void loadDone() {
        if (news_swipe_refresh.isRefreshing()) {
            news_swipe_refresh.setRefreshing(false);
        }
        if (news_pb_loading != null && news_pb_loading.getVisibility() == View.VISIBLE) {
            news_pb_loading.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadError() {
        Toast.makeText(getActivity(), "获取攻略失败", Toast.LENGTH_SHORT).show();
        if (news_pb_loading != null && news_pb_loading.getVisibility() == View.VISIBLE) {
            news_pb_loading.setVisibility(View.GONE);
        }
        news_rv_list.setVisibility(View.GONE);
        reuse_no_connection.setVisibility(View.VISIBLE);
        if (news_swipe_refresh.isRefreshing()) {
            news_swipe_refresh.setRefreshing(false);
        }
    }

    //Fragment界面切换事件
    public void onEventMainThread(EBUISwitch busNine) {
        if ("NewsFragment".equals(busNine.getFrom())) {
            if (busNine.getPosition() == 2) {
                if (news_pb_loading.getVisibility() == View.VISIBLE) {
                    adapter.addList(0);
                }
            }
        }
    }

    //连接上网络事件
    public void onEventMainThread(EBNetworkState busNetworkState) {
        if (busNetworkState.isNetworkConnected()) {
            if (reuse_no_connection.getVisibility() == View.VISIBLE) {
                news_rv_list.setVisibility(View.VISIBLE);
                news_pb_loading.setVisibility(View.VISIBLE);
                reuse_no_connection.setVisibility(View.GONE);
                adapter = new News3FragmentAdapter(this, news_tv_label, true);
                news_rv_list.setAdapter(adapter);
            } else if (adapter.isNetworkError()) {
                adapter.setNetworkError(false);
                adapter.notifyItemChanged(adapter.getItemCount() - 1);
                adapter.addList(adapter.getAllListSize());
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AppController.canclePendingRequests(TAG);
        news_rv_list = null;
        layoutManager = null;
        adapter = null;
        news_pb_loading = null;
        reuse_no_connection = null;
        news_tv_label = null;
        news_rl_label = null;
        rparams = null;
    }

    private Handler handler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!isDestroy) {
                adapter = new News3FragmentAdapter(News3Fragment.this, news_tv_label, true);
                news_rv_list.setAdapter(adapter);
            }
        }
    };

    @Override
    public void onRefresh() {
        handler.postDelayed(runnable, 1000);
    }
}
