package jp.sourceforge.nicoro;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

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

public class ListMenuActivity extends FragmentActivity
implements Handler.Callback, WebBrowserFragmentStarter {
    public static final String INTENT_EXTRA_BOOKMARKS_ADD_URL = "BOOKMARKS_ADD_URL";
    public static final String INTENT_EXTRA_BOOKMARKS_ADD_TITLE = "BOOKMARKS_ADD_TITLE";
    /**
     * 現状vとidどちらでも可
     */
    public static final String INTENT_EXTRA_VIDEO_NUMBER = "VIDEO_NUMBER";
    public static final String INTENT_EXTRA_DEFAULT_LIST_RADIO = "DEFAULT_LIST_RADIO";

    private static final int MSG_ID_START_BROWSER = 1;

    private Context mContext;
    private MenuInflater mMenuInflater;

    private ListMenuView mListMenuView;

    private boolean mOnNewIntent;
    private boolean mResumed = false;

    private final HandlerWrapper mHandler = new HandlerWrapper(this);

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_ID_START_BROWSER:
                String url = (String) msg.obj;
                MainFragmentActivity.startBrowserActivity(
                        ListMenuActivity.this, url);
//                finish();
                break;
        }
        return true;
    }

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

        mContext = getApplicationContext();
        mMenuInflater = getMenuInflater();

        setContentView(R.layout.list_menu);
        mListMenuView = ViewUtil.findViewById(this, R.id.list_menu_root);

        LayoutInflater inflater = LayoutInflater.from(this);
        mListMenuView.onCreateView(inflater);
        mListMenuView.setFragmentManager(getSupportFragmentManager());
        mListMenuView.setIntent(getIntent());
        mListMenuView.onOrientationChanged(getResources().getConfiguration().orientation,
                false);

        // TODO ここでのintentそのまま使って良かったどうか
        mListMenuView.updateListMenu(getIntent());

        // 明示的に後からcheckしてFragment生成
        mListMenuView.checkDefaultListRadio();

        mOnNewIntent = false;
    }

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

        APILevelWrapper api = APILevelWrapper.createInstance();
        api.setDisplayHomeAsUpEnabled_ActionBar(api.getActionBar(this), true);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mResumed = true;

        // 表示直後のIntent処理はFragment側から行う

        if (mOnNewIntent) {
            Intent intent = getIntent();
            updateFragmentBookmarks(intent);
            updateFragmentRelatedVideo(intent);
            updateFragmentListMenu(intent);
            mOnNewIntent = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mResumed = false;

        mListMenuView.setCurrentRadioToDefaultRadio();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mOnNewIntent = true;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (MainFragmentActivity.isDualPane(newConfig)) {
            if (mResumed) {
                // TODO 表示中のリストメニュー項目をdual paneに引き継ぎたい
                MainFragmentActivity.startBrowserActivity(this, null);
            }
            finish();
        } else {
            mListMenuView.onOrientationChanged(newConfig.orientation, false);
        }
    }

    void updateFragmentBookmarks(Intent intent) {
        BookmarksFragment bookmarks = findFragmentInListMenu(
                BookmarksFragment.class);
        ListMenuView.updateFragmentBookmarks(intent, bookmarks);
    }

    void updateFragmentRelatedVideo(Intent intent) {
        RelatedVideoFragment relatedVideo = findFragmentInListMenu(
                RelatedVideoFragment.class);
        ListMenuView.updateFragmentRelatedVideo(intent, relatedVideo);
    }
    void updateFragmentListMenu(Intent intent) {
        mListMenuView.updateListMenu(intent);
    }

    <T extends Fragment> T findFragmentInListMenu(Class<T> clz) {
        return mListMenuView.findFragment(clz);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMenuInflater.inflate(R.menu.list_menu_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
//            case R.id.menu_top:
//                mHandler.obtainMessage(MSG_ID_START_BROWSER,
//                        "http://www.nicovideo.jp/").sendToTarget();
//                return true;
            case R.id.menu_config:
                intent = new Intent(mContext, NicoroConfig.class);
                startActivity(intent);
                return true;
            case R.id.menu_help:
                intent = new Intent(mContext, NicoroHelp.class);
                startActivity(intent);
                return true;
            case R.id.menu_search:
                onSearchRequested();
                return true;
            case R.id.menu_exit:
                NavUtils.navigateUpFromSameTask(this);
                return true;
            case R.id.menu_last_url:
                mHandler.obtainMessage(MSG_ID_START_BROWSER
                        ).sendToTarget();
                return true;
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
            default:
//                assert false : item.getItemId();
                break;
        }
        return false;
    }

    @Override
    public void startWebBrowserFragment(String url) {
        mHandler.obtainMessage(MSG_ID_START_BROWSER, url).sendToTarget();
    }
}
