package com.czbix.v2ex.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.czbix.v2ex.AppCtx;
import com.czbix.v2ex.R;
import com.czbix.v2ex.common.exception.FatalException;
import com.czbix.v2ex.dao.ConfigDao;
import com.czbix.v2ex.dao.NodeDao;
import com.czbix.v2ex.eventbus.BusEvent;
import com.czbix.v2ex.model.Node;
import com.czbix.v2ex.model.Page;
import com.czbix.v2ex.model.Tab;
import com.czbix.v2ex.model.Topic;
import com.czbix.v2ex.ui.SearchActivity;
import com.czbix.v2ex.ui.adapter.TopicAdapter;
import com.czbix.v2ex.ui.adapter.TopicAdapter.OnTopicActionListener;
import com.czbix.v2ex.ui.loader.AsyncTaskLoader.LoaderResult;
import com.czbix.v2ex.ui.loader.TopicListLoader;
import com.czbix.v2ex.ui.widget.DividerItemDecoration;
import com.czbix.v2ex.util.ExceptionUtils;
import com.czbix.v2ex.util.LogUtils;
import com.google.common.eventbus.Subscribe;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnTopicActionListener} interface
 * to handle interaction events.
 * Use the {@link TopicListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TopicListFragment extends Fragment implements LoaderCallbacks<LoaderResult<List<Topic>>>, SwipeRefreshLayout.OnRefreshListener {
    private static final String TAG = TopicListFragment.class.getSimpleName();
    private static final String ARG_PAGE = "page";

    private Page mPage;

    private OnTopicActionListener mListener;
    private TopicAdapter mAdapter;
    private SwipeRefreshLayout mLayout;
    private TopicListLoader mLoader;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TopicListFragment.
     */
    public static TopicListFragment newInstance(Page page) {
        TopicListFragment fragment = new TopicListFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PAGE, page);
        fragment.setArguments(args);
        return fragment;
    }

    public TopicListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle arguments = getArguments();
        if (arguments != null) {
            mPage = arguments.getParcelable(ARG_PAGE);
        }

        if (mPage == null) {
            throw new FatalException("node can't be null");
        }

        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mLayout = (SwipeRefreshLayout) inflater.inflate(R.layout.fragment_topic_list,
                container, false);
        RecyclerView recyclerView = ((RecyclerView) mLayout.findViewById(R.id.recycle_view));

        mLayout.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mLayout.getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

        mAdapter = new TopicAdapter(mListener);
        recyclerView.setAdapter(mAdapter);

        mLayout.setRefreshing(true);
        return mLayout;
    }

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

        boolean shouldSetTitle;
        if (mPage instanceof Node) {
            Node node = (Node) mPage;
            if (!node.hasInfo()) {
                node = NodeDao.get(node.getName());
                if (node == null) {
                    return;
                }
                mPage = node;
            }
            shouldSetTitle = true;
        } else if (mPage == Tab.TAB_FAV_TOPIC) {
            shouldSetTitle = true;
        } else {
            shouldSetTitle = false;
        }

        if (shouldSetTitle) {
            getActivity().setTitle(mPage.getTitle());
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        AppCtx.getEventBus().register(this);

        if (ConfigDao.get(ConfigDao.KEY_NODE_ETAG, null) != null) {
            onNodesLoadFinish(null);
        }
    }

    @Subscribe
    public void onNodesLoadFinish(BusEvent.GetNodesFinishEvent e) {
        final LoaderManager loaderManager = getLoaderManager();
        if (loaderManager.getLoader(0) != null) {
            // already loaded
            return;
        }
        loaderManager.initLoader(0, null, this);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mListener = ((OnTopicActionListener) activity);
    }

    @Override
    public void onStop() {
        super.onStop();

        AppCtx.getEventBus().unregister(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();

        mListener = null;
    }

    @Override
    public Loader<LoaderResult<List<Topic>>> onCreateLoader(int id, Bundle args) {
        LogUtils.d(TAG, "load list: %s", mPage.getTitle());

        mLoader = new TopicListLoader(getActivity(), mPage);
        return mLoader;
    }

    @Override
    public void onLoadFinished(Loader<LoaderResult<List<Topic>>> loader, LoaderResult<List<Topic>> result) {
        mLayout.setRefreshing(false);
        if (result.hasException()) {
            ExceptionUtils.handleExceptionNoCatch(this, result.mException);
            return;
        }
        mAdapter.setDataSource(result.mResult);
    }

    @Override
    public void onLoaderReset(Loader<LoaderResult<List<Topic>>> loader) {
        mAdapter.setDataSource(null);
    }

    @Override
    public void onRefresh() {
        final Loader<?> loader = getLoaderManager().getLoader(0);
        if (loader == null) {
            return;
        }
        loader.forceLoad();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_topic_list, menu);

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_refresh:
                mLayout.setRefreshing(true);
                onRefresh();
                return true;
            case R.id.action_web_search:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

@@ -1001,16 +1001,55 @@
 .Topic;%0A
+import com.czbix.v2ex.ui.MainActivity;%0A
 import c
@@ -4218,24 +4218,95 @@
 nceState);%0A%0A
+        final MainActivity activity = ((MainActivity) getActivity());%0A%0A
         bool
@@ -4693,24 +4693,83 @@
 AV_TOPIC) %7B%0A
+            activity.setNavSelected(R.id.drawer_favorite);%0A
             
@@ -4897,29 +4897,24 @@
         
-getA
+a
 ctivity
-()
 .setTitl

fix bug for select favorite in drawer menu