package com.atid.at288n.app.demo.view;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.atid.at288.lib.Reader;
import com.atid.at288.lib.type.BankType;
import com.atid.at288.lib.type.ModelType;
import com.atid.at288.lib.type.SelectionActionType;
import com.atid.at288.lib.type.StoredModeType;
import com.atid.at288n.app.demo.IReaderActivity;
import com.atid.at288n.app.demo.R;
import com.atid.at288n.app.demo.type.ActionType;
import com.atid.at288n.app.demo.view.adapter.TagListAdapter;

public class StoredInventoryView extends BaseView implements Button.OnClickListener, OnItemSelectedListener {

	private TagListAdapter adapterTagList;

	private ArrayAdapter<CharSequence> adapterPowerGain;
	private Spinner spinPowerGain;

	private CheckBox chkStoredMode;


	private TextView txtTagCount;

	private Button btnInventory;
	private Button btnClear;
	private Button btnLoad;
	private Button btnDelete;

	private ModelType modelType = ModelType.AT288;
	private ActionType action = ActionType.Stop;
	private InitChecker initChecker = new InitChecker();

	public StoredInventoryView(Context context) {
		super(context);
		if (isInEditMode()) return;
		init(context);
	}

	public StoredInventoryView(Context context, AttributeSet attrs) {
		super(context, attrs);
		if (isInEditMode()) return;
		init(context);
	}

	private void init(Context context) {
		TAG = "StoredView";

		action = ActionType.Stop;

		if (!isInEditMode()) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			inflater.inflate(R.layout.view_stored_inventory, this, true);
		}
	}

	@Override
	public void onCreate(IReaderActivity parent, Reader reader) {
		super.onCreate(parent, reader);

		title = getResources().getString(R.string.stored_inventory_title);
		icon = R.drawable.ic_stored_inventory;

		// Initialize Widget
		initWidget();
		// Disable Widget
		enableWidget(false);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.read_inventory:
			if (ActionType.Stop == this.action) {
				reader.inventory(null);
				this.action = ActionType.Inventory;
			} else {
				reader.stopOperation();
				this.action = ActionType.Stop;
			}
			enableWidget(true);
			break;
		case R.id.clear:
			clearTagList();
			break;
		case R.id.stored_mode:
			reader.setStoredMode(this.chkStoredMode.isChecked() ? StoredModeType.Stored : StoredModeType.NotStored);
			break;
		case R.id.load_stored_data:
			clearTagList();
			enableWidget(false);
			showWaitDialog("","stored data is loading...");
			reader.getStoredData();
			break;
		case R.id.delete_stored_data:
			AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
			builder.setMessage(
					getResources().getString(R.string.delete_stored_data_label))
					.setCancelable(false)
					.setPositiveButton(
							getResources().getString(R.string.yes_button_label),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									showWaitDialog("","All stored data is deleting...");
									reader.deleteStoredData();
									clearTagList();
								}

							})
					.setNegativeButton(
							getResources().getString(R.string.no_button_label),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}

							});
			AlertDialog dlg = builder.create();
			dlg.setTitle(getResources().getString(
					R.string.delete_stored_data_title));
			dlg.setIcon(R.drawable.ic_question);
			dlg.show();
			break;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		Log.d(TAG, String.format("onItemSelected(%d, %d, %d)", parent.getId(), position, id));
		
		if (!initChecker.init)
			return;

		switch (parent.getId()) {
		case R.id.power_gain:
			// Change Power Gain...
			this.reader.setPowerEx(position);
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
	}

	@Override
	public void initView() {
		// Initalize Checker
		initChecker.init();
		// Disable Widget
		enableWidget(false);
		// Clear Tag List
		clearTagList();
		
		this.adapterTagList.setDisplayTid(false);
		
		InitTask requestParamsTask = new InitTask();
		requestParamsTask.execute();
	}
	
	public void requestParameters() {
		// Set Mask Memory Bank
		reader.setSelectionBank(BankType.EPC);
		// Set Mask Offset
		reader.setSelectionOffset(16);
		// Set Mask Action
		reader.setSelectionAction(SelectionActionType.Matching);

		// Request Global band
		reader.getGlobalBand();
		// Request All Extended Properties
		reader.getAllExtendedProperty();

		// Request Power Gain
		reader.getPowerEx();
		// Request Use Serial No
		reader.getUseSerialNo();
	}

	@Override
	public void exitView() {
		reader.stopOperation();
		this.action = ActionType.Stop;
		enableWidget(true);
	}

	@Override
	public void createView() {
	}

	public void createView(int Globalband) {
		
		if(adapterPowerGain != null) {
			return;
		}
		
		modelType = ModelType.valueOf(reader.getModelType());

		if (Globalband == 8)//Japan 1W 
		{
			adapterPowerGain = ArrayAdapter.createFromResource(getContext(),
							R.array.power_gain_array,
							android.R.layout.simple_spinner_dropdown_item);
		}
		else if (Globalband == 9)//Japan 0.25W
		{
			adapterPowerGain = ArrayAdapter.createFromResource(getContext(), 
							R.array.power_gain_japan_array,
							android.R.layout.simple_spinner_dropdown_item);
		}
		else if (Globalband == 12)//Japan 0.125W
		{
			adapterPowerGain = ArrayAdapter.createFromResource(getContext(), 
							R.array.power_gain_japan_array_125,
							android.R.layout.simple_spinner_dropdown_item);
		}
		else					//Normal
		{
			adapterPowerGain = ArrayAdapter.createFromResource(getContext(), 
							R.array.power_gain_array,
							android.R.layout.simple_spinner_dropdown_item);
		}
		
		spinPowerGain.setAdapter(adapterPowerGain);
	}

	@Override
	public void onReaderStateChange(int state) {
		Log.d(TAG, String.format("onReaderStateChange(%d)", state));

		if (state == Reader.STATE_LISTEN || state == Reader.STATE_NONE) {
			hideWaitDialog();
			parent.closeSubView();
		}
	}

	@Override
	public void onReaderReadTag(int event, String tag) {
		Log.d(TAG, String.format("onReaderReadTag(%d, %s)", event, tag));
		adapterTagList.addTag(tag);
		txtTagCount.setText("" + adapterTagList.getCount());
	}

	@Override
	public void onReaderResponse(int event, String code) {
		Log.d(TAG, String.format("onReaderResponse(%d, %s)", event, code));
	}

	@Override
	public void onReaderProperty(char code, String value) {
		Log.d(TAG, String.format("onReaderProperty(%c, %s)", code, value));
		switch (code) {
		case Reader.PROPERTY_CONTINUE_MODE:
			break;
		case Reader.PROPERTY_GLOBAL_BAND:
			int globalBand = Integer.parseInt(value);			
			createView(globalBand);
			break;
		}
	}

	@Override
	public void onReaderAction(char code) {
		Log.d(TAG, String.format("onReaderActionChange(%c)", code));
		switch (code) {
		case Reader.ACTION_STOP:
			action = ActionType.Stop;
			hideWaitDialog();
			break;
		default:
			action = ActionType.Inventory;
			break;
		}
		enableWidget(true);
	}

	@Override
	public void onReaderExtentedProperty(char code, String value) {
		Log.d(TAG, String.format("onReaderExtendedProperty(%c, %s)", code,
				value));
		enableWidget(true);
		
		switch (code) {
		case Reader.PROPERTY_EX_POWER_GAIN:
			spinPowerGain.setSelection(Integer.parseInt(value));
			checkInit(InitChecker.POWER);
			checkInit(InitChecker.CONTINUE_MODE);
			break;
		case Reader.PROPERTY_EX_STORED_MODE:
			chkStoredMode.setChecked(Integer.parseInt(value) > 0);
			checkInit(InitChecker.STORED_MODE);
			break;
		case Reader.PROPERTY_EX_USE_SERIAL_NO:
			checkInit(InitChecker.USE_SERIAL_NO);
			break;
		case Reader.PROPERTY_EX_GET_STORED_DATA:
			hideWaitDialog();
			enableWidget(true);
			break;
		case Reader.PROPERTY_EX_DELETE_STORED_DATA:
			hideWaitDialog();
			break;
		}
	}

	@Override
	public void onReaderTimeout() {
		Log.d(TAG, "onReaderTimeout()");
	}

	// =================================================================
	// MainActivity Widget Control Methods
	// =================================================================

	// Initialize Widget
	private void initWidget() {
		// Initialize tag listview
		this.adapterTagList = new TagListAdapter(getContext());
		ListView lstTag = (ListView) findViewById(R.id.tag_list);
		lstTag.setAdapter(adapterTagList);
		lstTag.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		// Initialize power gain spinner
		this.spinPowerGain = (Spinner) findViewById(R.id.power_gain);
		this.spinPowerGain.setPrompt(getResources().getString(
				R.string.power_gain_prompt_label));
		this.spinPowerGain.setOnItemSelectedListener(this);

		// Initialize stored mode checkbox
		this.chkStoredMode = (CheckBox) findViewById(R.id.stored_mode);
		this.chkStoredMode.setOnClickListener(this);

		// Initialize tag count textview
		this.txtTagCount = (TextView) findViewById(R.id.tag_count);

		// Initialize inventory button
		this.btnInventory = (Button) findViewById(R.id.read_inventory);
		this.btnInventory.setOnClickListener(this);

		// Initialize clear button
		this.btnClear = (Button) findViewById(R.id.clear);
		this.btnClear.setOnClickListener(this);

		// Initialize load stored data button
		this.btnLoad = (Button) findViewById(R.id.load_stored_data);
		this.btnLoad.setOnClickListener(this);

		// Initialize delete stored data button
		this.btnDelete = (Button) findViewById(R.id.delete_stored_data);
		this.btnDelete.setOnClickListener(this);
	}

	// Enable Widget
	private void enableWidget(boolean enabled) {
		if (enabled) {
			if (this.action == ActionType.Stop) {
				this.spinPowerGain.setEnabled(true);	
				this.chkStoredMode.setEnabled(true);
				this.btnInventory.setText(getResources().getString(
						R.string.read_inventory_button_label));
				this.btnInventory.setEnabled(true);
				this.btnClear.setEnabled(true);
				this.btnLoad.setEnabled(true);
				this.btnDelete.setEnabled(true);
			} else {
				this.spinPowerGain.setEnabled(false);
				this.chkStoredMode.setEnabled(false);
				this.btnInventory.setText(getResources().getString(
						R.string.stop_button_label));
				this.btnInventory.setEnabled(true);
				this.btnClear.setEnabled(false);
				this.btnLoad.setEnabled(false);
				this.btnDelete.setEnabled(false);
			}
		} else {
			this.spinPowerGain.setEnabled(false);
			this.chkStoredMode.setEnabled(false);
			this.btnInventory.setEnabled(false);
			this.btnClear.setEnabled(false);
			this.btnLoad.setEnabled(false);
			this.btnDelete.setEnabled(false);
		}
	}

	// Clear Tag List View
	private void clearTagList() {
		this.adapterTagList.clear();
		this.txtTagCount.setText("" + this.adapterTagList.getCount());
	}

	// Check Initialize Reader Service
	private void checkInit(int index) {
		if (initChecker.init)
			return;

		initChecker.check[index] = true;
		if (initChecker.isInitialized()) {
			initChecker.init = true;
			enableWidget(true);
		}
	}

	private ProgressDialog m_dlgWait = null;

	// Show Wait Dialog
	private void showWaitDialog(String title, String message) {
		hideWaitDialog();
		m_dlgWait = ProgressDialog.show(this.getContext(), title, message);
	}

	// Hide Wait Dialog
	private void hideWaitDialog() {
		if (m_dlgWait != null) {
			m_dlgWait.cancel();
			m_dlgWait = null;
		}
	}
	
	
	// =================================================================
	// Declare Internal Classes
	// =================================================================

	private class InitChecker {
		public static final int POWER = 0;
		public static final int CONTINUE_MODE = 1;
		public static final int STORED_MODE = 2;
		public static final int USE_SERIAL_NO = 3;

		public boolean init;
		public boolean[] check;

		public InitChecker() {
			init();
		}
		
		public void init() {
			init = false;
			check = new boolean[] { false, false, false, false };
		}

		private boolean isInitialized() {
			return !init && check[0] && check[1] && check[2] && check[3];
		}
	}
	
	private class InitTask extends AsyncTask<Void, Void, Void> {

		private Context context = StoredInventoryView.this.getContext();
		ProgressDialog asyncDialog = new ProgressDialog(context);
		
		@Override
		protected void onPreExecute() {
			asyncDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			asyncDialog.setMessage("wait for initialize");
			asyncDialog.setCancelable(false);
			asyncDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			
			requestParameters();
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			asyncDialog.dismiss();
			super.onPostExecute(result);
		}
		
	}

	@Override
	public void clearMaskParams() {
	}
}
