package jp.sourceforge.nicoro;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;

import jp.gr.java_conf.shiseissi.commonlib.CollUtil;

public class IndexFragment extends ListFragment {
    private static final String KEY_URL = "url";
    private static final String KEY_TITLE = "title";

    private ArrayList<HashMap<String, String>> mIndexList;

    private SimpleAdapter mAdapter;

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

        Resources res = getResources();
        String[] title = res.getStringArray(R.array.index);
        String[] url = res.getStringArray(R.array.index_url);
        assert title.length == url.length;
        int length = title.length;
        mIndexList = new ArrayList<HashMap<String, String>>(length);
        for (int i = 0; i < length; ++i) {
            HashMap<String, String> item = CollUtil.newHashMap(2);
            item.put(KEY_URL, url[i]);
            item.put(KEY_TITLE, title[i]);
            mIndexList.add(item);
        }

        // Theme使うのでActivity使用
        mAdapter = new SimpleAdapter(
                getActivity(),
                mIndexList,
                android.R.layout.simple_list_item_2,
                new String[] {KEY_TITLE, KEY_URL},
                new int[] {android.R.id.text1, android.R.id.text2}
                );
    }

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

    private void updateListView() {
        ListView listView = getListView();
        Resources res = getResources();
        int colorBG = res.getColor(R.color.index_background);
        listView.setBackgroundColor(colorBG);
        listView.setCacheColorHint(colorBG);
        setListAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Activity a = getActivity();
                if (a instanceof WebBrowserFragmentStarter) {
                    WebBrowserFragmentStarter starter =
                        (WebBrowserFragmentStarter) a;
                    String url = mIndexList.get(position).get(KEY_URL);
                    starter.startWebBrowserFragment(url);
                }
            }
        });
    }
}
