package jp.sourceforge.nicoro;

import android.support.v4.app.Fragment;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.RadioGroup;

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

public class ListMenuActivityTests extends ActivityInstrumentationTestCase2<ListMenuActivity> {
    private ListMenuActivity mActivity;

    @SuppressWarnings("deprecation")
    public ListMenuActivityTests() {
        super("jp.sourceforge.nicoro", ListMenuActivity.class);
    }

    @Override
    protected void tearDown() throws Exception {
        mActivity = null;
        super.tearDown();
    }

    public void testSelectMenu() throws Throwable {
        mActivity = getActivity();
        RadioGroup listMenu = ViewUtil.findViewById(mActivity, R.id.list_menu);

        assertEquals(R.id.radio_index, listMenu.getCheckedRadioButtonId());

        waitFragment(IndexFragment.class);

        check(listMenu, R.id.radio_ranking);
        waitFragment(RankingFragment.class);

        check(listMenu, R.id.radio_mylist);
        waitFragment(MylistFragment.class);

        check(listMenu, R.id.radio_video_tag);
        waitFragment(VideoTagFragment.class);

        check(listMenu, R.id.radio_related_video);
        waitFragment(RelatedVideoFragment.class);

        check(listMenu, R.id.radio_access_history);
        waitFragment(AccessHistoryFragment.class);

        check(listMenu, R.id.radio_bookmarks);
        waitFragment(BookmarksFragment.class);

        check(listMenu, R.id.radio_index);
        waitFragment(IndexFragment.class);
    }

    private void check(final RadioGroup radioGroup, final int id) throws Throwable {
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                radioGroup.check(id);
            }
        });
    }

    private void waitFragment(final Class<? extends Fragment> classFragment) {
        TestUtil.assertUntil(new TestUtil.Until() {
            private Fragment f;

            @Override
            public String errorMessage() {
                return "Wait: " + classFragment.getSimpleName()
                    + " but Current: " + f.toString();
            }

            @Override
            public boolean command() {
                f = mActivity.findFragmentInListMenu(classFragment);
                if (f == null) {
                    return false;
                }
                if (f.getClass() != classFragment) {
                    return false;
                }
                if (f.getId() != R.id.fragment_list) {
                    return false;
                }
                return f.isVisible();
            }
        });
    }
}
