package com.cusnews.app.fragments;

import java.util.List;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cusnews.R;
import com.cusnews.app.adapters.TopicListAdapter;
import com.cusnews.databinding.TopicListBinding;
import com.cusnews.ds.Topic;
import com.cusnews.ds.TopicsFactory;
import com.cusnews.utils.Prefs;

/**
 * A list of all topics that will be subscribed to push.
 *
 * @author Xinyue Zhao
 */
public final class TopicListFragment extends CusNewsFragment {
	/**
	 * Main layout for this component.
	 */
	private static final int LAYOUT = R.layout.fragment_topic_list;
	/**
	 * Pre-defined list of push-topics.
	 */
	private List<Topic> mTopicList;
	/**
	 * Data-binding.
	 */
	private TopicListBinding mBinding;

	public static TopicListFragment newInstance(Context context) {
		return (TopicListFragment) Fragment.instantiate(context, TopicListFragment.class.getName());
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mTopicList = TopicsFactory.create();
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(LAYOUT, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mBinding = DataBindingUtil.bind(view.findViewById(R.id.topic_list_rv));
		mBinding.topicListRv.setLayoutManager(new LinearLayoutManager(getActivity()));
		mBinding.setTopicsAdapter(new TopicListAdapter(mTopicList));
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Prefs prefs = Prefs.getInstance();
		prefs.setPushSelections(null);
		StringBuilder list = new StringBuilder();
		List<Topic> topics = mBinding.getTopicsAdapter().getData();
		for(Topic topic : topics) {
			list.append(topic.getApiName());
			list.append(",");
		}
		list.delete(list.length()-1, list.length());//Remove last ","
		prefs.setPushSelections(list.toString());
	}
}

@@ -2071,16 +2071,48 @@
 pics) %7B%0A
+%09%09%09if(topic.getSubscribed()) %7B%0A%09
 %09%09%09list.
@@ -2142,16 +2142,17 @@
 ());%0A%09%09%09
+%09
 list.app
@@ -2163,18 +2163,50 @@
 %22,%22);%0A%09%09
+%09
 %7D%0A
+%09%09%7D%0A%09%09if(list.length() %3E 0) %7B%0A%09
 %09%09list.d
@@ -2224,17 +2224,19 @@
 length()
--
+ - 
 1, list.
@@ -2263,16 +2263,20 @@
 ast %22,%22%0A
+%09%09%7D%0A
 %09%09prefs.

Fix problem of names of subscribed topics in setting.