package jp.sourceforge.nicoro;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;

public class SearchActivity extends Activity {

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

        Intent intent = getIntent();
        String action = intent.getAction();
        if (Intent.ACTION_SEARCH.equals(action)
                || (Intent.ACTION_VIEW.equals(action)
                        && intent.getFlags() == Intent.FLAG_ACTIVITY_NEW_TASK)) {
            search(intent);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        search(intent);
    }

    private void search(Intent intent) {
        final String query = intent.getStringExtra(SearchManager.QUERY);
        if (query == null) {
            finish();
            return;
        }

        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
                getApplicationContext(),
                NicoroSearchRecentSuggestionsProvider.AUTHORITY,
                NicoroSearchRecentSuggestionsProvider.DATABASE_MODE);
        suggestions.saveRecentQuery(query, null);

        if (query.startsWith("http://") || query.startsWith("https://")) {
            if (WebBrowserFragment.isInNicoVideoSite(query)) {
                MainFragmentActivity.startBrowserActivity(this, query);
            } else {
                Intent launchIntent = new Intent(
                        Intent.ACTION_VIEW, Uri.parse(query))
                    .addCategory(Intent.CATEGORY_BROWSABLE);
                startActivityIfNeeded(launchIntent, 0);
            }
            finish();
            return;
        }

        String ifUrl = "http://" + query;
        if (WebBrowserFragment.isInNicoVideoSite(ifUrl)) {
            MainFragmentActivity.startBrowserActivity(this, ifUrl);
            finish();
            return;
        }

        Resources res = getResources();
        String[] speeds = res.getStringArray(R.array.search_category_speed);
        final String[] urls = res.getStringArray(R.array.search_category_url);
        assert speeds.length == urls.length;

        int speedsLength = speeds.length;
        for (int i = 0; i < speedsLength; ++i) {
            String speed = speeds[i];
            int len = speed.length();
            if (query.length() > len && query.startsWith(speed)
                    && query.charAt(len) == ' ') {
                // 短縮キーワード検索
                String url = String.format(urls[i], query.substring(len + 1));
                MainFragmentActivity.startBrowserActivity(this, url);
                finish();
                return;
            }
        }

        // ダイアログのリストからカテゴリ選択
        String[] items = res.getStringArray(R.array.search_category);
        assert items.length == urls.length;
        DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which >= 0 && which < urls.length) {
                    String url = String.format(urls[which], query);
                    MainFragmentActivity.startBrowserActivity(SearchActivity.this, url);
                } else {
                    assert false;
                    Util.showErrorToast(getApplicationContext(), R.string.toast_search_fail);
                }
                finish();
            }
        };
        DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        };
        new AlertDialog.Builder(this)
            .setCancelable(true)
            .setTitle(R.string.dialog_title_search_category)
            .setItems(items, onClickListener)
            .setOnCancelListener(onCancelListener)
            .show();

//        Util.showErrorToast(getApplicationContext(), R.string.toast_search_fail);
//        finish();
    }
}
