package com.example.wordbook;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.example.wordbook.chart.IDemoChart;
import com.example.wordbook.chart.StatPieChart;
import com.example.wordbook.common.Common;
import com.example.wordbook.common.DBAccess;
import com.example.wordbook.common.Message;

/**
 * 統計画面クラス
 */
public class StatActivity extends Activity {

	/** TAG */
	private static final String TAG = StatActivity.class.getSimpleName();

	/** インスタンス状態用グラフ種別キー */
	private static final String IS_TYPE = "type";
	/** インスタンス状態用単語帳情報リストキー */
	private static final String IS_MAIN = "main";

	/** グラフ種別 */
	private int mType;
	/** 単語帳情報リスト */
	private List<Map<String, Object>> mMain;

	/** 統計データ */
	private Integer[] mStat = new Integer[3 * 8];

	/** グラフ色配列 */
	private int[] mColor = new int[8];
	/** 背景色配列 */
	private int[] mColorSub = new int[8];
	/** 凡例文字列 */
	private String[][] mLegend = new String[3][8];

	/** TextView */
	private TextView[][] mView = new TextView[4][8];
	/** ProgressBar */
	private ProgressBar mProg;
	/** LinearLayout */
	private LinearLayout mGraph;
	/** Spinner */
	private Spinner mSpinner;
	/** ToggleButton */
	private ToggleButton[] mButton = new ToggleButton[3];

	/*
	 * (非 Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate()");

		// レイアウト設定
		setContentView(R.layout.stat);

		// グラフ色配列取得
		TypedArray ta = getResources().obtainTypedArray(R.array.color);
		for (int i = 0; i < mColor.length; i++) {
			mColor[i] = ta.getColor(i, 0);
		}
		ta.recycle();
		// 背景色配列取得
		TypedArray taSub = getResources().obtainTypedArray(R.array.color_sub);
		for (int i = 0; i < mColorSub.length; i++) {
			mColorSub[i] = taSub.getColor(i, 0);
		}
		taSub.recycle();

		// 凡例文字列取得
		mLegend[0][0] = getString(R.string.item_level00);
		mLegend[0][1] = getString(R.string.item_level01);
		mLegend[0][2] = getString(R.string.item_level02);
		mLegend[0][3] = getString(R.string.item_level03);
		mLegend[0][4] = getString(R.string.item_level04);
		mLegend[0][5] = getString(R.string.item_level05);
		mLegend[0][6] = getString(R.string.item_level06);
		mLegend[0][7] = getString(R.string.item_level07);
		mLegend[1][0] = getString(R.string.item_flag00);
		mLegend[1][1] = getString(R.string.item_flag01);
		mLegend[1][2] = getString(R.string.item_flag02);
		mLegend[1][3] = getString(R.string.item_flag03);
		mLegend[1][4] = getString(R.string.item_flag04);
		mLegend[1][5] = getString(R.string.item_flag05);
		mLegend[1][6] = getString(R.string.item_flag06);
		mLegend[1][7] = getString(R.string.item_flag07);
		mLegend[2][0] = getString(R.string.item_record00);
		mLegend[2][1] = getString(R.string.item_record01);
		mLegend[2][2] = getString(R.string.item_record02);
		mLegend[2][3] = getString(R.string.item_record03);
		mLegend[2][4] = getString(R.string.item_record04);
		mLegend[2][5] = getString(R.string.item_record05);
		// 未使用欄
		mLegend[2][6] = "";
		mLegend[2][7] = "";

		// TextView取得
		mView[0][0] = (TextView) findViewById(R.id.tableRow0L);
		mView[0][1] = (TextView) findViewById(R.id.tableRow1L);
		mView[0][2] = (TextView) findViewById(R.id.tableRow2L);
		mView[0][3] = (TextView) findViewById(R.id.tableRow3L);
		mView[0][4] = (TextView) findViewById(R.id.tableRow4L);
		mView[0][5] = (TextView) findViewById(R.id.tableRow5L);
		mView[0][6] = (TextView) findViewById(R.id.tableRow6L);
		mView[0][7] = (TextView) findViewById(R.id.tableRow7L);
		mView[1][0] = (TextView) findViewById(R.id.tableRow0F);
		mView[1][1] = (TextView) findViewById(R.id.tableRow1F);
		mView[1][2] = (TextView) findViewById(R.id.tableRow2F);
		mView[1][3] = (TextView) findViewById(R.id.tableRow3F);
		mView[1][4] = (TextView) findViewById(R.id.tableRow4F);
		mView[1][5] = (TextView) findViewById(R.id.tableRow5F);
		mView[1][6] = (TextView) findViewById(R.id.tableRow6F);
		mView[1][7] = (TextView) findViewById(R.id.tableRow7F);
		mView[2][0] = (TextView) findViewById(R.id.tableRow0R);
		mView[2][1] = (TextView) findViewById(R.id.tableRow1R);
		mView[2][2] = (TextView) findViewById(R.id.tableRow2R);
		mView[2][3] = (TextView) findViewById(R.id.tableRow3R);
		mView[2][4] = (TextView) findViewById(R.id.tableRow4R);
		mView[2][5] = (TextView) findViewById(R.id.tableRow5R);
		mView[2][6] = (TextView) findViewById(R.id.tableRow6R);
		mView[2][7] = (TextView) findViewById(R.id.tableRow7R);
		mView[3][0] = (TextView) findViewById(R.id.tableRow0);
		mView[3][1] = (TextView) findViewById(R.id.tableRow1);
		mView[3][2] = (TextView) findViewById(R.id.tableRow2);
		mView[3][3] = (TextView) findViewById(R.id.tableRow3);
		mView[3][4] = (TextView) findViewById(R.id.tableRow4);
		mView[3][5] = (TextView) findViewById(R.id.tableRow5);
		mView[3][6] = (TextView) findViewById(R.id.tableRow6);
		mView[3][7] = (TextView) findViewById(R.id.tableRow7);

		// ProgressBar取得
		mProg = (ProgressBar) findViewById(R.id.progressBar);
		// LinearLayout取得
		mGraph = (LinearLayout) findViewById(R.id.layoutGraph);

		// 状態復帰
		if (savedInstanceState != null) {
			mType = savedInstanceState.getInt(IS_TYPE);
			mMain = (List<Map<String, Object>>) savedInstanceState
					.getSerializable(IS_MAIN);
		} else {
			mType = 0;
			mMain = Common.getWordbookPrefList(getApplicationContext());
		}
		Log.d(TAG, "type=" + mType + "/main=" + mMain.size());

		// データ無し
		if (mMain.size() == 0) {
			// エラー表示
			Message.show(getApplicationContext(), Message.ID.DATA_NOT_FOUND);
		}

		// スピナ用イベントリスナ設定
		mSpinner = (Spinner) findViewById(R.id.spinnerFile);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		for (Map<String, Object> item : mMain) {
			adapter.add(item.get(Common.WORDBOOK_TITLE).toString());
		}
		mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				doClickListItem(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		mSpinner.setAdapter(adapter);

		// ボタン用イベントリスナ設定
		mButton[0] = (ToggleButton) findViewById(R.id.toggleButtonLevel);
		mButton[0].setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				doClickToggleButton(0);
				delGraph();
				addGraph();
			}
		});
		mButton[1] = (ToggleButton) findViewById(R.id.toggleButtonFlag);
		mButton[1].setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				doClickToggleButton(1);
				delGraph();
				addGraph();
			}
		});
		mButton[2] = (ToggleButton) findViewById(R.id.toggleButtonRecord);
		mButton[2].setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				doClickToggleButton(2);
				delGraph();
				addGraph();
			}
		});
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "onResume()");
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "onPause()");

		// タスク動作時はキャンセル
		if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
			Log.w(TAG, "onPause()=RUNNING");
			// キャンセル
			mTask.cancel(true);
		}
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(TAG, "onSaveInstanceState()");

		// 状態保存
		outState.putSerializable(IS_TYPE, mType);
		outState.putSerializable(IS_MAIN, (Serializable) mMain);
	}

	/**
	 * グラフ種別ボタンクリック処理
	 * 
	 * @param type
	 *            選択種別
	 */
	private void doClickToggleButton(int type) {
		Log.d(TAG, "doClickToggleButton() type=" + type);

		switch (type) {
		case 0: // level
			mType = 0;
			mButton[0].setChecked(true);
			mButton[1].setChecked(false);
			mButton[2].setChecked(false);
			for (int i = 0; i < 8; i++) {
				// 統計データ背景色
				mView[0][i].setBackgroundColor(mColorSub[i]);
				mView[1][i].setBackgroundColor(Color.WHITE);
				mView[2][i].setBackgroundColor(Color.WHITE);
				// 凡例表示
				mView[3][i].setText(mLegend[0][i]);
				mView[3][i].setBackgroundColor(mColorSub[i]);
			}
			break;
		case 1: // flag
			mType = 1;
			mButton[0].setChecked(false);
			mButton[1].setChecked(true);
			mButton[2].setChecked(false);
			for (int i = 0; i < 8; i++) {
				// 統計データ背景色
				mView[0][i].setBackgroundColor(Color.WHITE);
				mView[1][i].setBackgroundColor(mColorSub[i]);
				mView[2][i].setBackgroundColor(Color.WHITE);
				// 凡例表示
				mView[3][i].setText(mLegend[1][i]);
				mView[3][i].setBackgroundColor(mColorSub[i]);
			}
			break;
		case 2: // record
			mType = 2;
			mButton[0].setChecked(false);
			mButton[1].setChecked(false);
			mButton[2].setChecked(true);
			for (int i = 0; i < 8; i++) {
				// 統計データ背景色
				mView[0][i].setBackgroundColor(Color.WHITE);
				mView[1][i].setBackgroundColor(Color.WHITE);
				mView[2][i].setBackgroundColor(mColorSub[i]);
				// 凡例表示
				mView[3][i].setText(mLegend[2][i]);
				mView[3][i].setBackgroundColor(mColorSub[i]);
			}
			// 未使用欄
			for (int i = 6; i < 8; i++) {
				mView[2][i].setBackgroundColor(Color.WHITE);
				mView[3][i].setBackgroundColor(Color.WHITE);
			}
			break;
		default:
			Log.w(TAG, "doClickToggleButton() type=" + type);
			break;
		}
	}

	/**
	 * 単語帳情報リストクリック処理
	 * 
	 * @param pos
	 *            選択位置
	 */
	private void doClickListItem(int pos) {
		Log.d(TAG, "doClickListItem() pos=" + pos);

		// 選択アイテム統計データ取得
		loadData((Integer) mMain.get(pos).get(Common.WORDBOOK_INDEX));
	}

	/**
	 * グラフ削除
	 */
	private void delGraph() {

		// プログレスバー以外削除
		if (mGraph.getChildCount() > 1) {
			mGraph.removeViewAt(1);
		}
	}

	/**
	 * グラフ追加
	 */
	private void addGraph() {

		// データ生成
		int size = 0; // 該当データサイズ
		int start = 0; // 該当データ開始位置
		switch (mType) {
		case 0: // level(0-7)
			size = 8;
			start = 0;
			break;
		case 1: // flag(8-15)
			size = 8;
			start = 8;
			break;
		case 2: // record(16-21)
			size = 6;
			start = 16;
			break;
		default:
			Log.w(TAG, "addGraph() type=" + mType);
			break;
		}
		double[] stat = new double[size];
		int[] color = new int[size];
		for (int i = 0; i < size; i++) {
			stat[i] = mStat[start + i];
			color[i] = mColor[i];
		}

		// グラフ生成
		IDemoChart mChart = new StatPieChart("", mLegend[mType], stat, color);
		mGraph.addView(mChart.execute(getApplicationContext()));
	}

	/** 統計データ取得タスク */
	private AsyncTask<Void, Void, Integer[]> mTask = null;

	/**
	 * 統計データ取得タスク呼び出し
	 * 
	 * @param index
	 *            インデックス
	 */
	private void loadData(final int index) {

		// 統計データ取得タスク動作時は処理無し
		if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
			Log.w(TAG, "loadData()=RUNNING");
			return;
		}

		// 統計データ取得タスク実行
		mTask = new AsyncTask<Void, Void, Integer[]>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				Log.d(TAG, "onPreExecute()");

				// 無効化
				for (View view : mButton) {
					view.setEnabled(false);
				}
				mSpinner.setClickable(false);

				// グラフ削除
				delGraph();
				// プログレスバー表示
				mProg.setVisibility(View.VISIBLE);
			}

			@Override
			protected void onPostExecute(Integer[] result) {

				// 統計データ保存
				for (int i = 0; i < 24; i++) {
					mStat[i] = result[i];
				}
				// 統計データ表示
				for (int i = 0; i < 3; i++) {
					for (int j = 0; j < 8; j++) {
						mView[i][j].setText(mStat[i * 8 + j].toString());
					}
				}
				// 未使用欄
				for (int j = 6; j < 8; j++) {
					mView[2][j].setText("");
				}
				// 凡例処理
				doClickToggleButton(mType);

				// プログレスバー非表示
				mProg.setVisibility(View.GONE);
				// グラフ追加
				addGraph();

				// 有効化
				for (View view : mButton) {
					view.setEnabled(true);
				}
				mSpinner.setClickable(true);

				Log.d(TAG, "onPostExecute()");
				super.onPostExecute(result);
			}

			@Override
			protected Integer[] doInBackground(Void... params) {
				Log.d(TAG, "doInBackground()=" + index);

				// 単語帳DB統計取得
				return DBAccess.getDBStat(getApplicationContext(), index);
			};
		}.execute();

	}

}
