package com.example.wordbook;

import java.io.UnsupportedEncodingException;

import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.text.style.TypefaceSpan;
import android.util.Log;

import com.example.wordbook.common.Common;

/**
 * 設定画面クラス
 */
public class PrefActivity extends PreferenceActivity implements
		OnPreferenceChangeListener, OnPreferenceClickListener {

	/** TAG */
	private static final String TAG = PrefActivity.class.getSimpleName();

	/** 基本設定用キー */
	private static final String[] mKeyList = { Common.PREF_TYPE,
			Common.PREF_MODE, Common.PREF_SORT, Common.PREF_SUITE,
			Common.PREF_ICON, Common.PREF_COMM };

	/** フィルタ設定用キー */
	private static final String[] mKeyCheck = { Common.PREF_RECORD + "0",
			Common.PREF_RECORD + "1", Common.PREF_RECORD + "2",
			Common.PREF_RECORD + "3", Common.PREF_RECORD + "4",
			Common.PREF_RECORD + "5", Common.PREF_FLAG + "0",
			Common.PREF_FLAG + "1", Common.PREF_FLAG + "2",
			Common.PREF_FLAG + "3", Common.PREF_FLAG + "4",
			Common.PREF_FLAG + "5", Common.PREF_FLAG + "6",
			Common.PREF_FLAG + "7", Common.PREF_LEVEL + "0",
			Common.PREF_LEVEL + "1", Common.PREF_LEVEL + "2",
			Common.PREF_LEVEL + "3", Common.PREF_LEVEL + "4",
			Common.PREF_LEVEL + "5", Common.PREF_LEVEL + "6",
			Common.PREF_LEVEL + "7" };

	/** 文字列設定用キー */
	private static final String[] mKeyText = { Common.PREF_FLAGITEM + "0",
			Common.PREF_FLAGITEM + "1", Common.PREF_FLAGITEM + "2",
			Common.PREF_FLAGITEM + "3", Common.PREF_FLAGITEM + "4",
			Common.PREF_FLAGITEM + "5", Common.PREF_FLAGITEM + "6",
			Common.PREF_FLAGITEM + "7" };

	/** 背景色配列 */
	private int[] mColorSub = new int[mKeyText.length];

	/*
	 * (非 Javadoc)
	 * 
	 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
	 */
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate()");

		// レイアウト設定
		addPreferencesFromResource(R.xml.preference);

		// 初期サマリ＋イベントリスナ設定
		ListPreference pref_list;
		for (String key : mKeyList) {
			pref_list = (ListPreference) findPreference(key);
			pref_list.setSummary(pref_list.getValue());
			pref_list.setOnPreferenceChangeListener(this);
		}

		Preference pref = findPreference(Common.PREF_FILTER);
		pref.setSummary(getFilterSummary());
		pref.setOnPreferenceClickListener(this);

		// 初期サマリ設定
		pref = findPreference(Common.PREF_STRINGS);
		pref.setSummary(getString(R.string.msg_summary_strings));
		pref = findPreference(Common.PREF_STAT);
		pref.setSummary(getString(R.string.msg_summary_stat));
		pref = findPreference(Common.PREF_MANAGE);
		pref.setSummary(getString(R.string.msg_summary_manage));
		pref = findPreference(Common.PREF_VERSION);
		pref.setSummary(Common.getVersionInfo(getApplicationContext()));
		pref = findPreference(Common.PREF_SYSTEM);
		pref.setSummary(Common.getSystemInfo(getApplicationContext()));

		// イベントリスナ設定
		CheckBoxPreference pref_check;
		for (String key : mKeyCheck) {
			pref_check = (CheckBoxPreference) findPreference(key);
			pref_check.setOnPreferenceChangeListener(this);
		}

		// 背景色配列取得
		TypedArray taSub = getResources().obtainTypedArray(R.array.color_sub);
		for (int i = 0; i < mColorSub.length; i++) {
			mColorSub[i] = taSub.getColor(i, 0);
		}
		taSub.recycle();

		// 初期サマリ＋イベントリスナ＋背景色設定
		EditTextPreference pref_text;
		for (int i = 0; i < mKeyText.length; i++) {
			pref_text = (EditTextPreference) findPreference(mKeyText[i]);
			pref_text.setSummary(getStringsSummary(pref_text.getText(), i));
			pref_text.setOnPreferenceChangeListener(this);
		}
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see android.app.Activity#finish()
	 */
	@Override
	public void finish() {

		// 設定画面から戻った後はメイン画面で必要な情報を更新すること
		// 応答設定
		Intent intent = getIntent();
		setResult(RESULT_OK, intent);

		super.finish();
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see
	 * android.preference.Preference.OnPreferenceChangeListener#onPreferenceChange
	 * (android.preference.Preference, java.lang.Object)
	 */
	@SuppressWarnings("deprecation")
	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		String key = preference.getKey();

		// 更新サマリ設定
		for (int i = 0; i < mKeyList.length; i++) {
			if (key.equals(mKeyList[i])) {
				preference.setSummary(newValue.toString());
				return true;
			}
		}
		for (int i = 0; i < mKeyCheck.length; i++) {
			if (key.equals(mKeyCheck[i])) {
				preference.setSummary(newValue.toString());
				return true;
			}
		}

		// 更新サマリ＋背景色設定
		EditTextPreference pref_text;
		for (int i = 0; i < mKeyText.length; i++) {
			if (key.equals(mKeyText[i])) {
				pref_text = (EditTextPreference) findPreference(key);
				pref_text.setSummary(getStringsSummary(newValue.toString(), i));
				return true;
			}
		}

		return true;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see
	 * android.preference.Preference.OnPreferenceClickListener#onPreferenceClick
	 * (android.preference.Preference)
	 */
	@Override
	public boolean onPreferenceClick(Preference preference) {

		// 親画面サマリ設定
		if (preference != null) {
			if (preference instanceof PreferenceScreen) {
				if (((PreferenceScreen) preference).getDialog() != null) {
					((PreferenceScreen) preference).getDialog()
							.setOnDismissListener(new OnDismissListener() {
								@SuppressWarnings("deprecation")
								@Override
								public void onDismiss(DialogInterface dialog) {
									Preference pref = findPreference(Common.PREF_FILTER);
									pref.setSummary(getFilterSummary());
									getListView().invalidateViews();
								}
							});
				}
			}
		}

		return false;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see android.preference.PreferenceActivity#onPreferenceTreeClick(android.
	 * preference.PreferenceScreen, android.preference.Preference)
	 */
	@SuppressWarnings("deprecation")
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		super.onPreferenceTreeClick(preferenceScreen, preference);

		// https://code.google.com/p/android/issues/detail?id=4611
		if (preference != null) {
			if (preference instanceof PreferenceScreen) {
				if (((PreferenceScreen) preference).getDialog() != null) {
					((PreferenceScreen) preference)
							.getDialog()
							.getWindow()
							.getDecorView()
							.setBackgroundDrawable(
									this.getWindow().getDecorView()
											.getBackground().getConstantState()
											.newDrawable());
				}
			}
		}

		return false;
	}

	/**
	 * フィルタサマリ取得
	 * 
	 * @return フィルタサマリ
	 */
	private SpannableString getFilterSummary() {
		boolean[] record = Common.getRecordList(getApplicationContext());
		boolean[] flag = Common.getFlagList(getApplicationContext());
		boolean[] level = Common.getLevelList(getApplicationContext());
		String record_str = getString(R.string.label_record);
		String flag_str = getString(R.string.label_flag);
		String level_str = getString(R.string.label_level);
		final char LS = '\n';
		final char SP = ' '; // 半角
		final char SP2 = '　'; // 全角
		final char ON = 'O';
		final char OFF = 'X';

		// 各項目と半角全角が一致していること
		String colon = getString(R.string.label_colon);
		// コロンのバイト数で半角全角を判断
		boolean zen = false;
		try {
			zen = colon.getBytes("UTF-8").length == 1 ? false : true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 位置調整
		int len = 0;
		if (len < record_str.length()) {
			len = record_str.length();
		}
		if (len < flag_str.length()) {
			len = flag_str.length();
		}
		if (len < level_str.length()) {
			len = level_str.length();
		}

		// 文字列生成
		StringBuilder sb = new StringBuilder();
		sb.append(record_str + colon + SP);
		for (int i = record_str.length(); i < len; i++) {
			sb.append(zen ? SP2 : SP);
		}
		for (boolean item : record) {
			sb.append(item ? ON : OFF);
		}
		sb.append(LS);
		sb.append(flag_str + colon + SP);
		for (int i = flag_str.length(); i < len; i++) {
			sb.append(zen ? SP2 : SP);
		}
		for (boolean item : flag) {
			sb.append(item ? ON : OFF);
		}
		sb.append(LS);
		sb.append(level_str + colon + SP);
		for (int i = level_str.length(); i < len; i++) {
			sb.append(zen ? SP2 : SP);
		}
		for (boolean item : level) {
			sb.append(item ? ON : OFF);
		}
		SpannableString ss = new SpannableString(sb);

		// 等幅フォント
		ss.setSpan(new TypefaceSpan("monospace"), 0, ss.length(),
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

		return ss;
	}

	/**
	 * 文字列サマリ取得
	 * 
	 * @param str
	 *            文字列
	 * @param index
	 *            背景色インデックス
	 * @return 文字列サマリ
	 */
	private SpannableString getStringsSummary(String str, int index) {
		SpannableString ss = new SpannableString(str);

		// 背景色
		ss.setSpan(new BackgroundColorSpan(mColorSub[index]), 0, ss.length(),
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

		return ss;
	}

}
