/*
 * Copyright (C) 2008,2009  OMRON SOFTWARE Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.gorry.android.input.nicownng;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.inputmethodservice.InputMethodService;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;

/**
 * The OpenWnn IME's base class.
 *
 * @author Copyright (C) 2009 OMRON SOFTWARE CO., LTD.  All Rights Reserved.
 */
public class NicoWnnG extends InputMethodService {
	//private static final String GETACTION_INTERCEPT = "net.gorry.android.input.nicownng.ACTION_INTERCEPT";
	//private static final String INPUTCONNECTION_KEY = "inputconnection_key";
	private static final String ACTION_INTERCEPT = "com.adamrocker.android.simeji.ACTION_INTERCEPT";
	private static final String CATEGORY_KEY = "com.adamrocker.android.simeji.REPLACE";
	private static final String REPLACE_KEY = "replace_key";
	private static final String INPUTCONNECTION_KEY = "inputconnection_key";


	// dic.setup
	public static final String writableJAJPBaseName = new String("writableJAJP.dic");
	public static final String writableENBaseName   = new String("writableEN.dic");

	public static final String writableJAJPDic = new String("/data/data/net.gorry.android.input.nicownng/writableJAJP.dic");
	public static final String writableENDic   = new String("/data/data/net.gorry.android.input.nicownng/writableEN.dic");

	public static final String INPUTMODE_NICO   = new String("input_nico");
	public static final String INPUTMODE_BELL   = new String("input_bell");
	public static final String INPUTMODE_NORMAL = new String("input_normal");
	public static final String INPUTMODE_NICO2  = new String("input_nico2");
	public static final String INPUTMODE_TEST   = new String("input_test");
	public static final String INPUTMODE_2TOUCH = new String("input_2touch");

	/** Candidate view */
//	protected CandidatesViewManager  mCandidatesViewManager = null;
	protected TextCandidatesViewManager  mCandidatesViewManager = null;
	/** Input view (software keyboard) */
	protected InputViewManager  mInputViewManager = null;
	protected String            mInputViewMode    = INPUTMODE_NORMAL;
	protected boolean           mInputViewFullScreenInLandscape = false;

	/** Conversion engine */
	protected WnnEngine  mConverter = null;
	/** Pre-converter (for Romaji-to-Kana input, Hangul input, etc.) */
	protected LetterConverter  mPreConverter = null;
	/** The inputing/editing string */
	protected ComposingText  mComposingText = null;
	/** The input connection */
	public InputConnection mInputConnection = null;
	/** Auto hide candidate view */
	protected boolean mAutoHideMode = true;
	/** Direct input mode */
	protected boolean mDirectInputMode = true;
	/** CandidatesView is Shown */
	protected boolean mCandidatesViewIsShown = false;

	/** Flag for checking if the previous down key event is consumed by OpenWnn  */
	private boolean mConsumeDownEvent;

	/**
	 * Constructor
	 */
	public NicoWnnG() {
		super();
	}

	/***********************************************************************
	 * InputMethodService
	 **********************************************************************/
	/** @see android.inputmethodservice.InputMethodService#onCreate */
	@Override public void onCreate() {
		super.onCreate();

		initializeEasySetting();
		convertOldPreferces();

		if (mConverter != null) { mConverter.init(); }
		if (mComposingText != null) { mComposingText.clear(); }

		registerMushroomReceiver();
	}

	/** @see android.inputmethodservice.InputMethodService#onCreateCandidatesView */
	@Override public View onCreateCandidatesView() {
		if (mCandidatesViewManager != null) {
			final WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
			final View view = mCandidatesViewManager.initView(this,
					wm.getDefaultDisplay().getWidth(),
					wm.getDefaultDisplay().getHeight());
			mCandidatesViewManager.setViewType(CandidatesViewManager.VIEW_TYPE_NORMAL);
			return view;
		} else {
			return super.onCreateCandidatesView();
		}
	}

	/** @see android.inputmethodservice.InputMethodService#onCreateInputView */
	@Override public View onCreateInputView() {

		if (mInputViewManager != null) {
			final WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
			return mInputViewManager.initView(this,
					wm.getDefaultDisplay().getWidth(),
					wm.getDefaultDisplay().getHeight());
		} else {
			return super.onCreateInputView();
		}
	}

	/** @see android.inputmethodservice.InputMethodService#onDestroy */
	@Override public void onDestroy() {
		super.onDestroy();

		unregisterMushroomReceiver();
		close();
	}

	/** @see android.inputmethodservice.InputMethodService#onKeyDown */
	@Override public boolean onKeyDown(final int keyCode, final KeyEvent event) {
		mConsumeDownEvent = onEvent(new NicoWnnGEvent(event));
		if (!mConsumeDownEvent) {
			return super.onKeyDown(keyCode, event);
		}
		return mConsumeDownEvent;
	}

	/** @see android.inputmethodservice.InputMethodService#onKeyUp */
	@Override public boolean onKeyUp(final int keyCode, final KeyEvent event) {
		boolean ret = mConsumeDownEvent;
		if (!ret) {
			ret = super.onKeyUp(keyCode, event);
		}else{
			onEvent(new NicoWnnGEvent(event));
		}
		return ret;
	}

	/** @see android.inputmethodservice.InputMethodService#onStartInput */
	@Override public void onStartInput(final EditorInfo attribute, final boolean restarting) {
		super.onStartInput(attribute, restarting);
		mInputConnection = getCurrentInputConnection();
		if (mComposingText != null) {
			mComposingText.clear();
		}
	}

	/** @see android.inputmethodservice.InputMethodService#onStartInputView */
	@Override public void onStartInputView(final EditorInfo attribute, final boolean restarting) {
		final boolean isPortrait = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
		setOrientPrefKeyMode(isPortrait);

		super.onStartInputView(attribute, restarting);
		mInputConnection = getCurrentInputConnection();

		setCandidatesViewShown(false);
		if (mInputConnection != null) {
			mDirectInputMode = false;
			if (mConverter != null) { mConverter.init(); }
		} else {
			mDirectInputMode = true;
		}
		final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		if (mCandidatesViewManager != null) { mCandidatesViewManager.setPreferences(pref);  }
		if (mInputViewManager != null) { mInputViewManager.setPreferences(pref, attribute);  }
		if (mPreConverter != null) { mPreConverter.setPreferences(pref);  }
		if (mConverter != null) { mConverter.setPreferences(pref);  }
	}

	/** @see android.inputmethodservice.InputMethodService#requestHideSelf */
	@Override public void requestHideSelf(final int flag) {
		super.requestHideSelf(flag);
		if (mInputViewManager == null) {
			hideWindow();
		}
	}

	/** @see android.inputmethodservice.InputMethodService#setCandidatesViewShown */
	@Override public void setCandidatesViewShown(final boolean shown) {
		super.setCandidatesViewShown(shown);
		if (shown) {
			showWindow(true);
		} else {
			if (mAutoHideMode && (mInputViewManager == null)) {
				hideWindow();
			}
		}
		mCandidatesViewIsShown = shown;
	}

	/** @see android.inputmethodservice.InputMethodService#hideWindow */
	@Override public void hideWindow() {
		super.hideWindow();
		mDirectInputMode = true;
		hideStatusIcon();
	}
	/** @see android.inputmethodservice.InputMethodService#onComputeInsets */
	@Override public void onComputeInsets(final InputMethodService.Insets outInsets) {
		super.onComputeInsets(outInsets);
		outInsets.contentTopInsets = outInsets.visibleTopInsets;
	}


	/**********************************************************************
	 * OpenWnn
	 **********************************************************************/
	/**
	 * Process an event.
	 *
	 * @param  ev  An event
	 * @return  {@code true} if the event is processed in this method; {@code false} if not.
	 */
	public boolean onEvent(final NicoWnnGEvent ev) {
		return false;
	}

	/**
	 * Search a character for toggle input.
	 *
	 * @param prevChar     The character input previous
	 * @param toggleTable  Toggle table
	 * @param reverse      {@code false} if toggle direction is forward, {@code true} if toggle direction is backward
	 * @return          A character ({@code null} if no character is found)
	 */
	protected String searchToggleCharacter(final String prevChar, final String[] toggleTable, final boolean reverse) {
		if (toggleTable == null) {
			return null;
		}
		for (int i = 0; i < toggleTable.length; i++) {
			if (prevChar.equals(toggleTable[i])) {
				if (reverse) {
					i--;
					if (i < 0) {
						return toggleTable[toggleTable.length - 1];
					} else {
						return toggleTable[i];
					}
				} else {
					i++;
					if (i == toggleTable.length) {
						return toggleTable[0];
					} else {
						return toggleTable[i];
					}
				}
			}
		}
		return null;
	}

	protected void close() {
		if (mConverter != null) { mConverter.close(); }
	}

	/**
	 * @return mCandidatesViewIsShown
	 */
	public boolean isCandidatesViewShown() {
		return mCandidatesViewIsShown;
	}


	/**
	 *
	 */
	public void openPreferenceSetting() {
		final Intent intent = new Intent(
				NicoWnnG.this, NicoWnnGControlPanelJAJP.class
		);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	/**
	 *
	 */
	public void openHelp() {
		final Intent intent = new Intent(
				NicoWnnG.this, NicoWnnGMain.class
		);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	/**
	 *
	 */
	public void reloadFlags() {
		final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		mInputViewFullScreenInLandscape = pref.getBoolean("fullscreen", false);
	}

	/**
	 *
	 */
	public String getComposingText(final int layer) {
		return mComposingText.toString(layer);
	}

	/**
	 *
	 */
	private boolean bPrefKeyIsPortrait = false;

	public void setOrientPrefKeyMode(final boolean isPortrait) {
		bPrefKeyIsPortrait = isPortrait;
	}

	public boolean getOrientPrefKeyMode() {
		return bPrefKeyIsPortrait;
	}

	public String getOrientPrefString(final SharedPreferences pref, final String key, final String defValue) {
		if (bPrefKeyIsPortrait) {
			return (pref.getString(key + "_portrait", defValue));
		}
		return (pref.getString(key + "_landscape", defValue));
	}

	public int getOrientPrefInteger(final SharedPreferences pref, final String key, final int defValue) {
		if (bPrefKeyIsPortrait) {
			return (pref.getInt(key + "_portrait", defValue));
		}
		return (pref.getInt(key + "_landscape", defValue));
	}

	public boolean getOrientPrefBoolean(final SharedPreferences pref, final String key, final Boolean defValue) {
		if (bPrefKeyIsPortrait) {
			return (pref.getBoolean(key + "_portrait", defValue));
		}
		return (pref.getBoolean(key + "_landscape", defValue));
	}

	public void convertOldPreferces() {
		final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		if ( !pref.getBoolean("new_preference_20110417a", false) ) {
			final SharedPreferences.Editor editor = pref.edit();

			// copyOldPreferenceString(pref, editor, "mainview_height_mode");
			// copyOldPreferenceString(pref, editor, "mainview_height_mode2");
			copyOldPreferenceString(pref, editor, "qwerty_kana_mode");
			copyOldPreferenceBoolean(pref, editor, "qwerty_matrix_mode");
			// copyOldPreferenceString(pref, editor, "nicoflick_mode");
			// copyOldPreferenceString(pref, editor, "flick_sensitivity_mode");
			// copyOldPreferenceString(pref, editor, "input_mode");
			copyOldPreferenceBoolean(pref, editor, "auto_caps");
			copyOldPreferenceBoolean(pref, editor, "is_skip_space");
			copyOldPreferenceBoolean(pref, editor, "nospace_candidate2");
			// copyOldPreferenceString(pref, editor, "candidateview_height_mode");
			// copyOldPreferenceString(pref, editor, "candidateview_height_mode2");
			copyOldPreferenceBoolean(pref, editor, "change_noalpha_qwerty");
			copyOldPreferenceBoolean(pref, editor, "change_nonumber_qwerty");
			copyOldPreferenceBoolean(pref, editor, "no_flip_screen");

			{
				final String name = "input_mode";
				String n1 = NicoWnnG.INPUTMODE_NORMAL;
				String n2 = NicoWnnG.INPUTMODE_NORMAL;
				if (pref.contains(name)) {
					final String str = pref.getString(name, NicoWnnG.INPUTMODE_NORMAL);
					n1 = str;
					n2 = str;
					editor.remove(name);
					editor.putString(name + "_portrait", n1);
					editor.putString(name + "_landscape", n2);
				}
			}

			{
				final String name = "change_alphanum_12key";
				int n1 = 1;
				int n2 = 0;
				if (pref.contains(name)) {
					final Boolean b = pref.getBoolean(name, false);
					n1 = (b ? 1 : 0);
					n2 = (b ? 1 : 0);
					editor.remove(name);
					editor.putBoolean(name + "_portrait", (n1 != 0));
					editor.putBoolean(name + "_landscape", (n2 != 0));
				}
			}

			{
				final String name = "change_kana_12key";
				int n1 = 1;
				int n2 = 0;
				if (pref.contains(name)) {
					final Boolean b = pref.getBoolean(name, false);
					n1 = (b ? 1 : 0);
					n2 = (b ? 1 : 0);
					editor.remove(name);
					editor.putBoolean(name + "_portrait", (n1 != 0));
					editor.putBoolean(name + "_landscape", (n2 != 0));
				}
			}

			{
				final String name = "candidateview_height_mode2";
				int n = 2;
				if (pref.contains(name)) {
					final String str = pref.getString(name, "2");
					if (name.equals("candidateview_value_0")) {
						n = 0;
					} else if (name.equals("candidateview_value_1")) {
						n = 1;
					} else if (name.equals("candidateview_value_2")) {
						n = 2;
					} else if (name.equals("candidateview_value_3")) {
						n = 3;
					} else if (name.equals("candidateview_value_4")) {
						n = 4;
					}
					editor.remove(name);
					editor.putString(name + "_portrait", String.valueOf(n));
					editor.putString(name + "_landscape", String.valueOf(n));
				}
			}

			{
				final String name = "mainview_height_mode2";
				int n = 2;
				if (pref.contains(name)) {
					final String str = pref.getString(name, "2");
					if (name.equals("mainview_value_0")) {
						n = 0;
					} else if (name.equals("mainview_value_1")) {
						n = 1;
					} else if (name.equals("mainview_value_2")) {
						n = 2;
					} else if (name.equals("mainview_value_3")) {
						n = 3;
					} else if (name.equals("mainview_value_4")) {
						n = 4;
					}
					editor.remove(name);
					editor.putString(name + "_portrait", String.valueOf(n));
					editor.putString(name + "_landscape", String.valueOf(n));
				}
			}

			{
				final String name = "nicoflick_mode";
				int n = 0;
				if (pref.contains(name)) {
					final String str = pref.getString(name, "0");
					if (name.equals("normal_stroke")) {
						n = 1;
					} else if (name.equals("nico_stroke")) {
						n = 2;
					}
					editor.remove(name);
					editor.putString(name + "_portrait", String.valueOf(n));
					editor.putString(name + "_landscape", String.valueOf(n));
				}
			}

			{
				final String name = "flick_sensitivity_mode";
				int n = 0;
				if (pref.contains(name)) {
					final String str = pref.getString(name, "1");
					if (name.equals("sensitivity_value_1")) {
						n = 1;
					} else if (name.equals("sensitivity_value_2")) {
						n = 2;
					} else if (name.equals("sensitivity_value_3")) {
						n = 3;
					} else if (name.equals("sensitivity_value_4")) {
						n = 4;
					}
					editor.remove(name);
					editor.putString(name + "_portrait", String.valueOf(n));
					editor.putString(name + "_landscape", String.valueOf(n));
				}
			}

			{
				final String name = "nico_candidate_mode";
				int portraitLine = 3;
				int landscapeLine = 1;
				if (pref.contains(name)) {
					final String lineMode = pref.getString(name, "1_1");
					if (lineMode.equals("1_1")) {
						portraitLine = 1;
						landscapeLine = 1;
					} else if (lineMode.equals("2_1")) {
						portraitLine = 2;
						landscapeLine = 1;
					} else if (lineMode.equals("1_2")) {
						portraitLine = 1;
						landscapeLine = 2;
					} else if (lineMode.equals("2_2")) {
						portraitLine = 2;
						landscapeLine = 2;
					}
					editor.remove("nico_candidate_mode");
					editor.putString("nico_candidate_lines" + "_portrait", String.valueOf(portraitLine));
					editor.putString("nico_candidate_lines" + "_landscape", String.valueOf(landscapeLine));
				}
			}

			editor.putBoolean("new_preference_20110417a", true);
			editor.commit();
		}
	}

	private void copyOldPreferenceString(final SharedPreferences pref, final SharedPreferences.Editor editor, final String key ) {
		if (pref.contains(key)) {
			final String value = pref.getString(key, "");
			editor.putString(key + "_portrait", value);
			editor.putString(key + "_landscape", value);
			editor.remove(key);
		}
	}

	private void copyOldPreferenceInteger(final SharedPreferences pref, final SharedPreferences.Editor editor, final String key ) {
		if (pref.contains(key)) {
			final int value = pref.getInt(key, 0);
			editor.putInt(key + "_portrait", value);
			editor.putInt(key + "_landscape", value);
			editor.remove(key);
		}
	}

	private void copyOldPreferenceBoolean(final SharedPreferences pref, final SharedPreferences.Editor editor, final String key ) {
		if (pref.contains(key)) {
			final boolean value = pref.getBoolean(key, false);
			editor.putBoolean(key + "_portrait", value);
			editor.putBoolean(key + "_landscape", value);
			editor.remove(key);
		}
	}

	/**
	 * mushroom
	 */

	private View vMushroomFocus;
	private String mMushroomWord = "";
	final private Handler hMushroom = new Handler();
	final private Runnable rMushroom = new Runnable() {
		public void run() {
			final InputConnection ic = getCurrentInputConnection();
			if (mMushroomWord != null) {
				if (mMushroomWord.length() > 0) {
					ic.commitText(mMushroomWord, 1);
				}
			}

			sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_CENTER);
		}
	};

	public void invokeMushroom(final String src) {
		hideWindow();
		final Intent intent = new Intent(
				this, Mushroom.class
		);
		intent.setAction("net.gorry.android.input.nicownng.ACTION_INTERCEPT");
		intent.putExtra("replace_key", src);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	private final MushroomReceiver mReceiver = new MushroomReceiver();

	public void registerMushroomReceiver() {
		final IntentFilter filter = new IntentFilter(Mushroom.ACTION);
		registerReceiver(mReceiver, filter);
	}

	public void unregisterMushroomReceiver() {
		unregisterReceiver(mReceiver);
	}

	public void onMushroom(final Context context, final Intent intent) {
		final Bundle extras = intent.getExtras();
		mMushroomWord = "";
		if (extras != null) {
			mMushroomWord = extras.getString("replace_key");
		}
		hMushroom.postDelayed(rMushroom, 250);
	}

	public class MushroomReceiver extends BroadcastReceiver {
		@Override
		public synchronized void onReceive(final Context context, final Intent intent) {
			onMushroom(context, intent);
		}

	}

	public void initializeEasySetting() {
		final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		if (pref.getString("mainview_height_mode2" + "_portrait", "").length() == 0) {
			// 画面サイズに合わせて初期キーボードサイズを設定
			WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();
			int shorter = display.getHeight();
			if (shorter > display.getWidth()) {
				shorter = display.getWidth();
			}
			int size = 1;
			if (shorter >= 320) size = 2;
			if (shorter > 480) size = 3;
			if (shorter > 600) size = 4;
			if (shorter > 720) size = 5;
			setEasySetting(1, size);
		}
	}
	
	public void setEasySetting(final int mode, final int size) {
		// final int size2 = (size>5) ? 5 : size;
		final int size2 = size;
		int different_pl = -1;
		int p_nicoflick_mode = -1;
		int p_flick_sensitivity_mode = -1;
		String p_input_mode = null;
		int p_change_kana_12key = -1;
		int p_change_alphanum_12key = -1;
		int p_size = -1;
		int p_maxline = -1;
		int p_candidateheight = -1;
		int p_textsize = -1;
		int l_nicoflick_mode = -1;
		int l_flick_sensitivity_mode = -1;
		String l_input_mode = null;
		int l_change_kana_12key = -1;
		int l_change_alphanum_12key = -1;
		int l_size = -1;
		int l_maxline = -1;
		int l_candidateheight = -1;
		int l_textsize = -1;
		switch (mode) {
		case 1:
			different_pl = 1;
			p_nicoflick_mode = 0;
			p_flick_sensitivity_mode = size2;
			p_input_mode = NicoWnnG.INPUTMODE_NORMAL;
			p_change_kana_12key = 1;
			p_change_alphanum_12key = 1;
			p_size = size;
			p_maxline = 3;
			p_candidateheight = size2;
			p_textsize = size2;
			l_nicoflick_mode = 0;
			l_flick_sensitivity_mode = size2;
			l_input_mode = NicoWnnG.INPUTMODE_NORMAL;
			l_change_kana_12key = 0;
			l_change_alphanum_12key = 0;
			l_size = size;
			l_maxline = 1;
			l_candidateheight = size2;
			l_textsize = size2;
			break;

		case 2:
			different_pl = 1;
			p_nicoflick_mode = 1;
			p_flick_sensitivity_mode = size2;
			p_input_mode = NicoWnnG.INPUTMODE_NORMAL;
			p_change_kana_12key = 1;
			p_change_alphanum_12key = 1;
			p_size = size;
			p_maxline = 3;
			p_candidateheight = size2;
			p_textsize = size2;
			l_input_mode = NicoWnnG.INPUTMODE_NORMAL;
			l_change_kana_12key = 0;
			l_change_alphanum_12key = 0;
			l_size = size;
			l_maxline = 1;
			l_nicoflick_mode = 0;
			l_flick_sensitivity_mode = size2;
			l_candidateheight = size2;
			l_textsize = size2;
			break;

		case 3:
			different_pl = 1;
			p_nicoflick_mode = 0;
			p_flick_sensitivity_mode = size2;
			p_input_mode = NicoWnnG.INPUTMODE_2TOUCH;
			p_change_kana_12key = 1;
			p_change_alphanum_12key = 1;
			p_size = size;
			p_maxline = 3;
			p_candidateheight = size2;
			p_textsize = size2;
			l_nicoflick_mode = 0;
			l_flick_sensitivity_mode = size2;
			l_input_mode = NicoWnnG.INPUTMODE_NORMAL;
			l_change_kana_12key = 0;
			l_change_alphanum_12key = 0;
			l_size = size;
			l_maxline = 1;
			l_candidateheight = size2;
			l_textsize = size2;
			break;

		case 4:
			different_pl = 1;
			p_nicoflick_mode = 0;
			p_flick_sensitivity_mode = size2;
			p_input_mode = NicoWnnG.INPUTMODE_NORMAL;
			p_change_kana_12key = 0;
			p_change_alphanum_12key = 0;
			p_size = size;
			p_maxline = 3;
			p_candidateheight = size2;
			p_textsize = size2;
			l_nicoflick_mode = 0;
			l_flick_sensitivity_mode = size2;
			l_input_mode = NicoWnnG.INPUTMODE_NORMAL;
			l_change_kana_12key = 0;
			l_change_alphanum_12key = 0;
			l_size = size;
			l_maxline = 1;
			l_candidateheight = size2;
			l_textsize = size2;
			break;

		}

		final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		final SharedPreferences.Editor editor = pref.edit();
		String pl;

		pl = "_portrait";
		if (different_pl >= 0) {
			editor.putBoolean("different_pl", (different_pl > 0) );
		}
		if (p_nicoflick_mode >= 0) {
			editor.putString("nicoflick_mode"+pl, String.valueOf(p_nicoflick_mode));
		}
		if (p_flick_sensitivity_mode >= 1) {
			editor.putString("flick_sensitivity_mode"+pl, String.valueOf(p_flick_sensitivity_mode-1));
		}
		if (p_input_mode != null) {
			editor.putString("input_mode"+pl, p_input_mode);
		}
		if (p_change_kana_12key >= 0) {
			editor.putBoolean("change_kana_12key"+pl, (p_change_kana_12key > 0) );
		}
		if (p_change_alphanum_12key >= 0) {
			editor.putBoolean("change_alphanum_12key"+pl, (p_change_alphanum_12key > 0) );
		}
		if (p_size >= 1) {
			editor.putString("mainview_height_mode2"+pl, String.valueOf(p_size-1));
		}
		if (p_maxline >= 1) {
			editor.putString("nico_candidate_lines"+pl, String.valueOf(p_maxline));
		}
		if (p_candidateheight >= 1) {
			editor.putString("candidateview_height_mode2"+pl, String.valueOf(p_candidateheight-1));
		}
		if (p_textsize >= 1) {
			editor.putString("candidate_font_size"+pl, String.valueOf(p_textsize-1));
		}

		pl = "_landscape";
		if (l_nicoflick_mode >= 0) {
			editor.putString("nicoflick_mode"+pl, String.valueOf(l_nicoflick_mode));
		}
		if (l_flick_sensitivity_mode >= 1) {
			editor.putString("flick_sensitivity_mode"+pl, String.valueOf(l_flick_sensitivity_mode-1));
		}
		if (l_input_mode != null) {
			editor.putString("input_mode"+pl, l_input_mode);
		}
		if (l_change_kana_12key >= 0) {
			editor.putBoolean("change_kana_12key"+pl, (l_change_kana_12key > 0) );
		}
		if (l_change_alphanum_12key >= 0) {
			editor.putBoolean("change_alphanum_12key"+pl, (l_change_alphanum_12key > 0) );
		}
		if (l_size >= 1) {
			editor.putString("mainview_height_mode2"+pl, String.valueOf(l_size-1));
		}
		if (l_maxline >= 1) {
			editor.putString("nico_candidate_lines"+pl, String.valueOf(l_maxline));
		}
		if (l_candidateheight >= 1) {
			editor.putString("candidateview_height_mode2"+pl, String.valueOf(l_candidateheight-1));
		}
		if (l_textsize >= 1) {
			editor.putString("candidate_font_size"+pl, String.valueOf(l_textsize-1));
		}

		editor.commit();

		reloadFlags();

	}


}
