package jp.sourceforge.nicoro;

import static jp.sourceforge.nicoro.Log.LOG_TAG;

//import jp.gr.java_conf.shiseissi.commonlib.APILevelWrapper;
import jp.sourceforge.nicoro.R;

import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
//import android.support.v4.app.NavUtils;
import android.view.MenuItem;

public class NicoroConfig extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
    private static final boolean DEBUG_LOGD = Release.IS_DEBUG & true;

	// 設定画面では扱わないオプションのキー
	public static final String COOKIE_USER_SESSION = "cookie_user_session";
	public static final String LAST_URL = "last_url";
	public static final String USER_AGENT = "user_agent";
    public static final String AUTHFLAG = "authflag";
    public static final String RANKING_CATEGORY = "ranking_category";
    public static final String RANKING_TERM = "ranking_term";
    public static final String RANKING_TARGET = "ranking_target";
    /**
     * {@link android.content.pm.ActivityInfo} の SCREEN_ORIENTATION_* を取る
     */
    public static final String PLAYER_SCREEN_ORIENTATION = "player_screen_orientation";

	private static final String MA = "ma";
	private static final String PW = "pw";

	private static int BIT = 0xc55c5cc5;

	private String mResPrefKeyWithoutFlash;
	private String mResPrefKeyLaunchFilterUrl;

	public NicoroConfig() {
	}

    @SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.nicoro_config);

		Resources res = getResources();
		mResPrefKeyWithoutFlash = res.getString(R.string.pref_key_without_flash);
		mResPrefKeyLaunchFilterUrl = res.getString(R.string.pref_key_launch_filter_url);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

    @SuppressWarnings("deprecation")
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
	        Preference preference) {
        String key = preference.getKey();
	    if (DEBUG_LOGD) {
	        // Android 1.6でエラーが出る？ので対策
	        try {
    	        Log.d(LOG_TAG, Log.buf().append(getClass().getSimpleName())
    	                .append("#onPreferenceTreeClick: preferenceScreen=")
    	                .append(preferenceScreen)
    	                .append(" preference=").append(preference)
    	                .append(" key=").append(key)
    	                .toString());
	        } catch (Exception e) {
	            Log.e(LOG_TAG, e.toString(), e);
	        }
	    }

	    if (key != null) {
    	    if (key.equals(mResPrefKeyWithoutFlash)) {
    	        CheckBoxPreference checkBox = (CheckBoxPreference) preference;
    	        if (!checkBox.isChecked()) {
    	            if (!isFlashPlayerInstalled()) {
    	                checkBox.setChecked(true);
    	                Util.showErrorToast(getApplicationContext(),
    	                        R.string.toast_flash_player_not_found);
    	                return true;
    	            }
    	        }
    	    }
	    }
        return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

    private boolean isFlashPlayerInstalled() {
        PackageInfo info = Util.getFlashPlayerInfo(this);
        if (info == null) {
            return false;
        }
        if (DEBUG_LOGD) {
            Log.d(LOG_TAG, Log.buf().append("flashplayer version=")
                    .append(info.versionName).toString());
        }
        return true;
    }

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

        // TODO 戻り先はDashBoardとログイン画面両方の可能性がある
//        APILevelWrapper api = APILevelWrapper.createInstance();
//        api.setDisplayHomeAsUpEnabled_ActionBar(this, true);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (mResPrefKeyLaunchFilterUrl.equals(key)) {
            PackageManager pm = getPackageManager();
            boolean launchFilterUrl = sharedPreferences.getBoolean(key, true);
            int enabled;
            if (launchFilterUrl) {
                enabled = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
            } else {
                enabled = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
            }
            String packageName = getPackageName();
            pm.setComponentEnabledSetting(
                    new ComponentName(packageName, packageName + ".LoginActivityUrl"),
                    enabled, PackageManager.DONT_KILL_APP);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // TODO 戻り先はDashBoardとログイン画面両方の可能性がある
                // TODO Advance画面にも個別に設定が必要
//                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // 設定画面とは関連のないメソッド

    public static String getMA(SharedPreferences sharedPreferences) {
		return convertXor(sharedPreferences.getString(MA, null));
	}
	public static String getPW(SharedPreferences sharedPreferences) {
		return convertXor(sharedPreferences.getString(PW, null));
	}
	/**
	 * {@link SharedPreferences.Editor#commit()} は後で自分で行うこと
	 * @param editor
	 * @param ma
	 */
	public static void putMA(SharedPreferences.Editor editor, String ma) {
		editor.putString(MA, convertXor(ma));
	}
	/**
	 * {@link SharedPreferences.Editor#commit()} は後で自分で行うこと
	 * @param editor
	 * @param pw
	 */
	public static void putPW(SharedPreferences.Editor editor, String pw) {
		editor.putString(PW, convertXor(pw));
	}

	static String convertXor(String src) {
		if (src == null) {
			return null;
		}
		final int len = src.length();
		char[] buf = new char[len];
		for (int i = 0; i < len; ++i) {
			buf[i] = (char) ((src.charAt(i) ^ BIT) & 0xffff);
		}
		return new String(buf);
	}

	public static String getCookieUserSession(SharedPreferences sp) {
	    return sp.getString(NicoroConfig.COOKIE_USER_SESSION, null);
	}

    public static String getCookieUserSession(Context context) {
        SharedPreferences sp = Util.getDefaultSharedPreferencesMultiProcess(context);
        return getCookieUserSession(sp);
    }

	/**
	 * UserSessionをSharedPreferencesに保存する<br>
	 * 既に保存済みの値と同じ場合は何もしない
	 * @param sp
	 * @param cookie
	 */
	public static void saveCookieUserSession(SharedPreferences sp, String cookie) {
	    if (cookie == null) {
	        return;
	    }
	    if (cookie.equals(getCookieUserSession(sp))) {
	        return;
	    }
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(NicoroConfig.COOKIE_USER_SESSION,
                cookie);
        editor.commit();
	}

	/**
	 * @see #saveCookieUserSession(SharedPreferences sp, String cookie)
	 * @param context
	 * @param cookie
	 */
    public static void saveCookieUserSession(Context context, String cookie) {
        SharedPreferences sp = Util.getDefaultSharedPreferencesMultiProcess(context);
        saveCookieUserSession(sp, cookie);
    }
}
