package com.halo.assistant.fragment.game;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.ArrayMap;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.GameNewsAdapter;
import com.gh.gamecenter.adapter.GameNewsTypeListAdapter;
import com.gh.gamecenter.eventbus.EBTypeChange;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * 游戏新闻搜索界面
 * <p>
 * Created by CsHeng on 14/12/2017.
 */
public class GameNewsSearchFragment extends ToolbarFragment {

    private RecyclerView mGameNewsRv;
    private RecyclerView mGameNewsTypeRv;
    private LinearLayout mNoDataLl;

    private GameNewsAdapter mGameNewsAdapter;
    private GameNewsTypeListAdapter mTypeListAdapter;
    private LinearLayoutManager mLayoutManager;
    private MenuItem mMenuItemSearch;

    private ArrayMap<String, GameNewsAdapter> mAdapterMap;
    private List<String> mTypeList;
    private String mGameId;
    private float mStartY = 0;

    public static GameNewsSearchFragment newInstance(String gameName, String gameId, String entrance) {
        final GameNewsSearchFragment fragment = new GameNewsSearchFragment();
        Bundle args = new Bundle();
        args.putString(EntranceConsts.KEY_GAMENAME, gameName);
        args.putString(EntranceConsts.KEY_GAMEID, gameId);
        args.putString(EntranceConsts.KEY_ENTRANCE, entrance);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_game_news_search;
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_search_white, menu);
        mMenuItemSearch = menu.findItem(R.id.menu_search);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_search) {
            mGameNewsRv.scrollToPosition(0);
            mGameNewsTypeRv.setVisibility(View.GONE);
            setMenuItemSearchVisibility(false);
            mGameNewsAdapter.openKeyBoard();
        }
        return super.onOptionsItemSelected(item);
    }

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

        setHasOptionsMenu(true);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mGameNewsRv = view.findViewById(R.id.game_news_list);
        mGameNewsTypeRv = view.findViewById(R.id.game_news_top_type_list);
        mNoDataLl = view.findViewById(R.id.reuse_none_data);
        TextView noDataTv = view.findViewById(R.id.reuseNoneDataTv);

        Bundle args = getArguments();

        if (args == null) return;

        String gameName = args.getString(EntranceConsts.KEY_GAMENAME);
        setNavigationTitle(gameName);

        noDataTv.setText("暂无内容");

        mAdapterMap = new ArrayMap<>();
        mTypeList = new ArrayList<>();

        mGameId = args.getString(EntranceConsts.KEY_GAMEID);

        mLayoutManager = new LinearLayoutManager(getContext());
        mGameNewsRv.setHasFixedSize(true);
        mGameNewsRv.setLayoutManager(mLayoutManager);
        mGameNewsRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mGameNewsAdapter != null && newState == RecyclerView.SCROLL_STATE_IDLE
                        && mLayoutManager.findLastVisibleItemPosition() == mGameNewsAdapter.getItemCount() - 1) {
                    if (!mGameNewsAdapter.isRemove() && !mGameNewsAdapter.isLoading() && !mGameNewsAdapter.isNetworkError()) {
                        mGameNewsAdapter.addList();
                    }
                }
            }

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

                if (mLayoutManager.findFirstVisibleItemPosition() >= 1) {
                    mGameNewsTypeRv.setVisibility(View.VISIBLE);
                    setMenuItemSearchVisibility(true);
                } else {
                    mGameNewsTypeRv.setVisibility(View.GONE);
                    setMenuItemSearchVisibility(false);
                }
            }
        });

        mGameNewsTypeRv.setHasFixedSize(true);
        mGameNewsTypeRv.setLayoutManager(new GridLayoutManager(getContext(), 5));

        //禁止由于滑动出现的阴影
        mGameNewsTypeRv.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mStartY = event.getY();
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                if (Math.abs(mStartY - event.getY()) > 0) {
                    return true;
                }
            }
            return false;
        });

        if (!TextUtils.isEmpty(mGameId)) {
            getGameArticleType();
        }
    }

    private void setMenuItemSearchVisibility(boolean visible) {
        if (mMenuItemSearch != null) {
            mMenuItemSearch.setVisible(visible);
        }
    }

    private void getGameArticleType() {
        RetrofitManager.getInstance().getApi()
                .getGameArticleType(mGameId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<String>>() {
                    @Override
                    public void onResponse(List<String> response) {
                        super.onResponse(response);
                        mTypeList = response;
                        mTypeList.add(0, "全部");
                        mGameNewsAdapter = new GameNewsAdapter(getContext(), mTypeList, mGameNewsRv, mGameId, "全部", mEntrance, mNoDataLl);
                        mAdapterMap.put("全部", mGameNewsAdapter);
                        mGameNewsRv.setAdapter(mGameNewsAdapter);

                        mTypeListAdapter = new GameNewsTypeListAdapter(getContext(), mTypeList, "全部");
                        mGameNewsTypeRv.setAdapter(mTypeListAdapter);

                        ViewGroup.LayoutParams params = mGameNewsTypeRv.getLayoutParams();
                        params.height = (int) Math.ceil(mTypeList.size() / 5f) * DisplayUtils.dip2px(getContext(), 35)
                                + DisplayUtils.dip2px(getContext(), 12);
                        mGameNewsTypeRv.setLayoutParams(params);
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        super.onFailure(e);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBTypeChange change) {
        mGameNewsAdapter = mAdapterMap.get(change.getType());
        if (mGameNewsAdapter == null) {
            mGameNewsAdapter = new GameNewsAdapter(getContext(), mTypeList, mGameNewsRv, mGameId, change.getType(), mEntrance, mNoDataLl);
            mAdapterMap.put(change.getType(), mGameNewsAdapter);
        }
        mGameNewsRv.setAdapter(mGameNewsAdapter);

        mGameNewsTypeRv.setVisibility(View.GONE);
        setMenuItemSearchVisibility(false);
        mTypeListAdapter.setNewsType(change.getType(), change.getPosition());
    }

}
