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.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.atid.at288.lib.Reader;
import com.atid.at288.lib.type.InventoryFormatType;
import com.atid.at288.lib.type.ModelType;
import com.atid.at288.lib.type.TagType;
import com.atid.at288n.app.demo.IReaderActivity;
import com.atid.at288n.app.demo.R;

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

	private static final int DEFAULT_SCAN_TIMEOUT = 6000;

	private static final int[] INVENTORY_TIME = { 10, 50, 80, 100, 150, 200,
			250, 300, 350, 400, 500, 600, 1000, 2000, 3000, 4000};
	private static final int[] INVENTORY_TIME_MA = { 10, 50, 80, 100, 150, 200,
			250, 300, 350, 400};
	private static final int[] IDLE_TIME = { 10, 20, 30, 50, 80, 100, 150,
			200, 250, 300, 400, 500, 600, 1000, 2000, 3000, 4000 };
	private static final int[] IDLE_TIME_MA = { 10, 20, 30, 50, 80, 100, 150,
			200, 250, 300, 400, 500, 600, 1000 };
	//private static final int[] SCAN_TIMEOUT = { 1000, 2000, 3000, 5000, 6000, 10000 };
	private static final int[] AUTO_POWER_OFF = {0, 10, 20, 30, 60, 90, 120, 150, 180, 240, 300, 360, 720,  1440};

	private ArrayAdapter<CharSequence> adapterTagType;
	private Spinner spinTagType;

	private ArrayAdapter<CharSequence> adapterReadType;
	private Spinner spinReadType;

	private ArrayAdapter<CharSequence> adapterPowerGain;
	private Spinner spinPowerGain;

	private ArrayAdapter<CharSequence> adapterInventoryTime;
	private Spinner spinInventoryTime;

	private ArrayAdapter<CharSequence> adapterIdleTime;
	private Spinner spinIdleTime;

	private ArrayAdapter<CharSequence> adapterGlobalBand;
	private TextView txtGlobalBand;
	private Spinner spinGlobalBand;
	private Button btnLBTChannel;

	//AT288N Only/////////////
	private ArrayAdapter<CharSequence> adapterAutoPowerOff;
	private Spinner spinAutoPowerOff;
	private TextView txtAutoPowerOff;
	private ArrayAdapter<CharSequence> adapterBeepMode;
	private Spinner spinBeepMode;
	private TextView txtBeepMode;
	//////////////////////////
	
	private ArrayAdapter<CharSequence> adapterInventoryFormat;
	private Spinner InventoryFormat;
	
	private TextView txtNationalCode;
	private EditText edtNationalCode;

	private TextView txtSerialNo;
	private EditText edtSerialNo;

	private Button btnBattery;
	private Button btnDefault;

	//private boolean adminMode = false;
	//private ModelType modelType = ModelType.AT288;
	//private int scanTimeout = DEFAULT_SCAN_TIMEOUT;
	private InitChecker initChecker = new InitChecker();
	
	private int g_GlobalBand_Now = 0;

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

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

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

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

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

		title = getResources().getString(R.string.option_title);
		icon = R.drawable.ic_option;

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

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.battery_state:
			reader.getBatteryState();
			break;
		case R.id.option_default:
			reader.defaultSettings();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
			// Set Continue Mode
			this.reader.setContinueMode(false);
			// Request Power Gain
			this.reader.getAllExtendedProperty();
			// Request Inventory Time
			this.reader.getPortInventoryTime();
			// Request Idle Time
			this.reader.getPortIdleTime();
			Toast.makeText(getContext(), "Success!! default parameters", Toast.LENGTH_SHORT).show();
			break;
		case R.id.lbt_channel:
			switch(g_GlobalBand_Now)
			{
				case 0:
				case 1:
				case 2:
				case 4:
				case 5:
				case 6:
				case 7:
				case 10:
				case 11:
				case 13:
				case 14:
				case 15:
				case 16:
				case 17:
				case 18:   //mkj
				case 19:
				case 20:
				case 21:
				case 22:
					break;
				case 8:
				case 9:
				case 12:
					showLBTChannelDialog(0);
					break;
			}
			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.tag_type:
			this.reader.setTagType(position == 0 ? TagType.ISO18000_6C_GEN2
					: TagType.ISO18000_6B);
			
			if(position == 1) {
				this.InventoryFormat.setAdapter(null);
				this.adapterInventoryFormat = ArrayAdapter.createFromResource(getContext(),
						R.array.inventory_format_array_ma,
						android.R.layout.simple_spinner_dropdown_item);
				this.InventoryFormat.setAdapter(this.adapterInventoryFormat);
			} else {
				this.InventoryFormat.setAdapter(null);
				this.adapterInventoryFormat = ArrayAdapter.createFromResource(getContext(),
						R.array.inventory_format_array,
						android.R.layout.simple_spinner_dropdown_item);
				this.InventoryFormat.setAdapter(this.adapterInventoryFormat);
			}
			
			break;
		case R.id.read_type:
			this.reader.setContinueModeExN(position);
			break;
		case R.id.power_gain:
			this.reader.setPowerEx(position);
			break;
		case R.id.inventory_time:
			this.reader.setPortInventoryTime(getInventoryTime());
			break;
		case R.id.idle_time:
			this.reader.setPortIdleTime(getIdleTime());
			break;
		case R.id.auto_poweeroff:
			this.reader.setAutoPowerOffTime(getAutoPowerOff());
			break;
		case R.id.beep_mode:
			this.reader.setBuzzer(position == 1);
			break;
		case R.id.global_band:
			int chage_GlobalBand = position;
			Log.d(TAG, String.format("onItemSelected   globalBand+++"));
			if(g_GlobalBand_Now ==8 || g_GlobalBand_Now ==9 || g_GlobalBand_Now ==12)//Japan(1W, 0.25W, 0.125W)
			{
				if(chage_GlobalBand != 8 || chage_GlobalBand != 9 || chage_GlobalBand != 12)
				{
					Toast.makeText(getContext(), getResources().getString(R.string.msg_result_NotSupport), Toast.LENGTH_LONG).show();
					spinGlobalBand.setSelection(g_GlobalBand_Now);
					return;
				}
			}
			else//Normal
			{
				if(chage_GlobalBand == 8 || chage_GlobalBand == 9 || chage_GlobalBand == 12)
				{
					Toast.makeText(getContext(), getResources().getString(R.string.msg_result_NotSupport), Toast.LENGTH_LONG).show();
					spinGlobalBand.setSelection(g_GlobalBand_Now);
					return;
				}
			}
			Log.d(TAG, String.format("onItemSelected   globalBand---"));
			this.reader.setGlobalBand(chage_GlobalBand);	
			break;
		case R.id.inventory_type:
			int type = position;
			switch(type){
			case 0: this.reader.setInventoryFormat(InventoryFormatType.PC_EPC); break;
			case 1: this.reader.setInventoryFormat(InventoryFormatType.SERIAL_PC_EPC);break;
			case 2: this.reader.setInventoryFormat(InventoryFormatType.ONLY_EPC);break;
			case 3: this.reader.setInventoryFormat(InventoryFormatType.SERIAL_EPC);break;
			}
			break;
			
		}

		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();

		txtNationalCode.setVisibility(View.VISIBLE);
		edtNationalCode.setVisibility(View.GONE);
		txtSerialNo.setVisibility(View.VISIBLE);
		edtSerialNo.setVisibility(View.GONE);
		
		if(reader.IsAT288N_MA()) {
			this.spinReadType.setAdapter(null);
			this.adapterReadType = ArrayAdapter.createFromResource(getContext(),
					R.array.read_type_array_ma,
					android.R.layout.simple_spinner_dropdown_item);
			this.spinReadType.setAdapter(this.adapterReadType);
		} else {
			this.spinReadType.setAdapter(null);
			this.adapterReadType = ArrayAdapter.createFromResource(getContext(),
					R.array.read_type_array,
					android.R.layout.simple_spinner_dropdown_item);
			this.spinReadType.setAdapter(this.adapterReadType);
		}
		
		// Enable Activity Widget
		enableWidget(false);

		InitTask requestParamsTask = new InitTask();
		requestParamsTask.execute();
	}
	
	public void requestParameters() {
		reader.getFirmwareVersion();
		
		// Request Global Band
		reader.getGlobalBand();
		// Request All Extended Properties
		reader.getAllExtendedProperty();
		// Request National Code
		reader.getNationalCode();
		// Request Serial No
		reader.getSerialNo();
		// Request Inventory Time
		reader.getPortInventoryTime();
		// Request Idle Time
		reader.getPortIdleTime();

		// Request InventoryForm
		reader.getInventoryFormat();
		
		reader.getAutoPowerOffTime(); //AT288N Only
		reader.getBuzzer(); //AT288N Only
	}

	
	@Override
	public void exitView() {
	}

	@Override
	public void createView() {		
	}

	public void createView(int Globalband) {
		// Initialize inventory time spinner
		this.adapterInventoryTime = ArrayAdapter.createFromResource(
				getContext(), 
				reader.IsAT288N_MA() ? R.array.inventory_time_ma_array : R.array.inventory_time_array,
				android.R.layout.simple_spinner_dropdown_item);
		this.spinInventoryTime.setAdapter(this.adapterInventoryTime);

		// Initialize idle time spinner
		this.adapterIdleTime = ArrayAdapter.createFromResource(getContext(),
				reader.IsAT288N_MA() ? R.array.idle_time_ma_array : R.array.idle_time_array,
				android.R.layout.simple_spinner_dropdown_item);
		this.spinIdleTime.setAdapter(this.adapterIdleTime);
		
		if(adapterPowerGain != null) {
			return;
		}
		
		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);	
		}
		
		txtGlobalBand.setVisibility(View.VISIBLE);
		spinGlobalBand.setVisibility(View.GONE);
		btnLBTChannel.setVisibility(View.GONE);
		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)
			parent.closeSubView();
	}

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

	@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_ANTENNA_SWITCHING_TIME:
			setInventoryTime(Integer.parseInt(value));
			checkInit(InitChecker.INVENTORY_TIME);
			break;
		case Reader.PROPERTY_POWER_IDLE_TIME:
			setIdleTime(Integer.parseInt(value));
			checkInit(InitChecker.IDLE_TIME);
			break;
		case Reader.PROPERTY_GLOBAL_BAND:
			int globalBand = Integer.parseInt(value);
			g_GlobalBand_Now = globalBand;
			
			if(reader.IsAT288N_MA()) {
				this.spinGlobalBand.setAdapter(null);
				this.adapterGlobalBand = ArrayAdapter.createFromResource(getContext(), 
						R.array.global_band_ma_array, android.R.layout.simple_spinner_dropdown_item);
				this.spinGlobalBand.setAdapter(this.adapterGlobalBand);
				txtGlobalBand.setText(getResources().getStringArray(
						R.array.global_band_ma_array)[globalBand]);
			} else {
				txtGlobalBand.setText(getResources().getStringArray(
						R.array.global_band_array)[globalBand]);
			}
			
			spinGlobalBand.setSelection(globalBand);
			checkInit(InitChecker.GLOBAL_BAND);
			
			createView(g_GlobalBand_Now);
			break;
		case Reader.PROPERTY_LBT_CHANNEL:
			showLBTChannelDialog(Integer.parseInt(value));
			break;
			
		case Reader.PROPERTY_AUTO_POWEROFF: //AT288N Only
			setAutoPowerOff(Integer.parseInt(value));
			break;
		case Reader.PROPERTY_BUZZER:
			spinBeepMode.setSelection(Integer.parseInt(value));
			break;
		}
	}

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

	@Override
	public void onReaderExtentedProperty(char code, String value) {
		Log.d(TAG,
				String.format("onReaderExtendedProperty(%c, %s)", code, value));
		switch (code) {
		case Reader.PROPERTY_EX_TAG_TYPE:
			spinTagType.setSelection(Integer.parseInt(value));
			checkInit(InitChecker.TAG_TYPE);
			if(reader.IsAT288N_MA())
				spinTagType.setEnabled(true); //AT288 Only 6C/6B Select , AT288N is Only 6C TagType
			else
				spinTagType.setEnabled(false);
			
			if(reader.TagType == Reader.ISO18000_6B && InventoryFormat.getCount() > 2) {
				this.InventoryFormat.setAdapter(null);
				this.adapterInventoryFormat = ArrayAdapter.createFromResource(getContext(),
						R.array.inventory_format_array_ma,
						android.R.layout.simple_spinner_dropdown_item);
				this.InventoryFormat.setAdapter(this.adapterInventoryFormat);
			} else if(reader.TagType == Reader.ISO18000_6C_GEN2 && InventoryFormat.getCount() < 4) {
				this.InventoryFormat.setAdapter(null);
				this.adapterInventoryFormat = ArrayAdapter.createFromResource(getContext(),
						R.array.inventory_format_array,
						android.R.layout.simple_spinner_dropdown_item);
				this.InventoryFormat.setAdapter(this.adapterInventoryFormat);
			}
			
			break;
		case Reader.PROPERTY_EX_CONTINUE_MODE:
			spinReadType.setSelection(Integer.parseInt(value));
			checkInit(InitChecker.READ_TYPE);
			break;
		case Reader.PROPERTY_EX_POWER_GAIN:
			spinPowerGain.setSelection(Integer.parseInt(value));
			checkInit(InitChecker.INVENTORY_TIME);
			checkInit(InitChecker.IDLE_TIME);
			checkInit(InitChecker.POWER);
			break;
		case Reader.PROPERTY_EX_USE_SERIAL_NO:
			InventoryFormat.setSelection(Integer.parseInt(value));
			checkInit(InitChecker.USE_SERIAL_NO);
			break;
		case Reader.PROPERTY_EX_BATTERY_STATE:
			String strValue;
			strValue = value.equals("0") ? "high" : "Low";
			strValue = "Battery State : " + strValue;
			Toast.makeText(getContext(), strValue, Toast.LENGTH_LONG).show();
			break;
		case Reader.PROPERTY_EX_NATIONAL_CODE:
			txtNationalCode.setText(value);
			edtNationalCode.setText(value);
			checkInit(InitChecker.NATIONAL_CODE);
			break;
		case Reader.PROPERTY_EX_SERIAL_NO:
			txtSerialNo.setText(value);
			edtSerialNo.setText(value);
			checkInit(InitChecker.SERIAL_NO);
			break;
		}
	}

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

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

	// Initialize Widget
	private void initWidget() {
		// Initialize tag type spinner
		this.spinTagType = (Spinner) findViewById(R.id.tag_type);
		this.spinTagType.setPrompt(getResources().getString(
				R.string.tag_type_prompt_label));
		this.spinTagType.setOnItemSelectedListener(this);
		this.adapterTagType = ArrayAdapter.createFromResource(getContext(),
				R.array.tag_type_array,
				android.R.layout.simple_spinner_dropdown_item);
		this.spinTagType.setAdapter(this.adapterTagType);

		//Initialize auto power off spinner   -   AT288N Only
		this.spinAutoPowerOff = (Spinner) findViewById(R.id.auto_poweeroff);
		this.spinAutoPowerOff.setPrompt(getResources().getString(R.string.auto_poweroff_label));
		this.spinAutoPowerOff.setOnItemSelectedListener(this);
		this.adapterAutoPowerOff = ArrayAdapter.createFromResource(getContext(), 
				R.array.auto_poweroff_array, android.R.layout.simple_spinner_dropdown_item);
		this.spinAutoPowerOff.setAdapter(this.adapterAutoPowerOff);
		this.txtAutoPowerOff = (TextView) findViewById(R.id.auto_poweroff_textview);
		
		//Initialize Beep Mode spinner - AT288N Only
		this.spinBeepMode = (Spinner) findViewById(R.id.beep_mode);
		this.spinBeepMode.setPrompt(getResources().getString(R.string.beep_mode_label));
		this.spinBeepMode.setOnItemSelectedListener(this);
		this.adapterBeepMode = ArrayAdapter.createFromResource(getContext(), 
				R.array.beep_mode, android.R.layout.simple_spinner_dropdown_item);
		this.spinBeepMode.setAdapter(this.adapterBeepMode);
		this.txtBeepMode = (TextView) findViewById(R.id.beep_mode_textview);

		// Initialize read type spinner
		this.spinReadType = (Spinner) findViewById(R.id.read_type);
		this.spinReadType.setPrompt(getResources().getString(
				R.string.read_type_prompt_label));
		this.spinReadType.setOnItemSelectedListener(this);
		this.adapterReadType = ArrayAdapter.createFromResource(getContext(),
				R.array.read_type_array,
				android.R.layout.simple_spinner_dropdown_item);
		this.spinReadType.setAdapter(this.adapterReadType);
		
		// 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 inventory time spinner
		this.spinInventoryTime = (Spinner) findViewById(R.id.inventory_time);
		this.spinInventoryTime.setPrompt(getResources().getString(
				R.string.inventory_time_prompt_label));
		this.spinInventoryTime.setOnItemSelectedListener(this);

		// Initialize idle time spinner
		this.spinIdleTime = (Spinner) findViewById(R.id.idle_time);
		this.spinIdleTime.setPrompt(getResources().getString(
				R.string.idle_time_prompt_label));
		this.spinIdleTime.setOnItemSelectedListener(this);

		// Initialize global band textview
		this.txtGlobalBand = (TextView) findViewById(R.id.global_band_value);

		// Initialize global band spinner
		this.spinGlobalBand = (Spinner) findViewById(R.id.global_band);
		this.spinGlobalBand.setPrompt(getResources().getString(
				R.string.global_band_prompt_label));
		this.spinGlobalBand.setOnItemSelectedListener(this);
		this.adapterGlobalBand = ArrayAdapter.createFromResource(getContext(),
				R.array.global_band_array,
				android.R.layout.simple_spinner_dropdown_item);
		this.spinGlobalBand.setAdapter(this.adapterGlobalBand);

		// Initailize LBT channel button
		this.btnLBTChannel = (Button) findViewById(R.id.lbt_channel);
		this.btnLBTChannel.setOnClickListener(this);

		// Initialize national code textview
		this.txtNationalCode = (TextView) findViewById(R.id.national_code_value);

		// Initialize national code edittext
		this.edtNationalCode = (EditText) findViewById(R.id.national_code);

		// Initialize serial no textview
		this.txtSerialNo = (TextView) findViewById(R.id.serial_no_value);

		// Initialize serial no edittext
		this.edtSerialNo = (EditText) findViewById(R.id.serial_no);

		// Battery State
		this.btnBattery = (Button) findViewById(R.id.battery_state);
		this.btnBattery.setOnClickListener(this);
		
		///////MKJ////
		this.InventoryFormat =(Spinner) findViewById(R.id.inventory_type);
		this.InventoryFormat.setPrompt(getResources().getString(R.string.inventory_format_prompt_lable));
		this.InventoryFormat.setOnItemSelectedListener(this);
		this.adapterInventoryFormat = ArrayAdapter.createFromResource(getContext(),
				R.array.inventory_format_array,
				android.R.layout.simple_spinner_dropdown_item);
		this.InventoryFormat.setAdapter(this.adapterInventoryFormat);

		// Initialize default button
		this.btnDefault = (Button) findViewById(R.id.option_default);
		this.btnDefault.setOnClickListener(this);
	}

	// Enable Widget
	private void enableWidget(boolean enabled) {
		if(!this.reader.IsAT288N_MA()){
			spinTagType.setEnabled(false); 
		}else{
			spinTagType.setEnabled(enabled);
		}
		spinReadType.setEnabled(enabled);
		spinPowerGain.setEnabled(enabled);
		spinInventoryTime.setEnabled(enabled);
		spinIdleTime.setEnabled(enabled);
		spinGlobalBand.setEnabled(enabled);
		btnLBTChannel.setEnabled(enabled);
		edtNationalCode.setEnabled(enabled);
		edtSerialNo.setEnabled(enabled);
		btnBattery.setEnabled(enabled);
		btnDefault.setEnabled(enabled);
		InventoryFormat.setEnabled(enabled);
	}

	// get inventory time
	private int getInventoryTime() {
		
		int[] inventoryTime = reader.IsAT288N_MA() ? INVENTORY_TIME_MA : INVENTORY_TIME;
		
		return inventoryTime[spinInventoryTime.getSelectedItemPosition()];
	}

	// get inventory time
	private void setInventoryTime(int value) {
		int[] inventoryTime = reader.IsAT288N_MA() ? INVENTORY_TIME_MA : INVENTORY_TIME;
		for (int i = 0; i < inventoryTime.length - 1; i++) {
			if ((inventoryTime[i] + inventoryTime[i + 1]) / 2 > value) {
				Log.d(TAG, String.format(
						"DEBUG. setInventoryTime(%d) - [%d, %d], {%d}", value,
						inventoryTime[i], inventoryTime[i + 1], i));
				spinInventoryTime.setSelection(i);
				return;
			}
		}
		Log.d(TAG, String.format("DEBUG. setInventoryTime(%d) - {%d}", value,
				inventoryTime.length - 1));
		spinInventoryTime.setSelection(inventoryTime.length - 1);
	}

	// get idle time
	private int getIdleTime() {
		int[] idleTime = reader.IsAT288N_MA() ? IDLE_TIME_MA : IDLE_TIME;
		
		return idleTime[spinIdleTime.getSelectedItemPosition()];
	}

	// get idle time
	private void setIdleTime(int value) {
		int[] idleTime = reader.IsAT288N_MA() ? IDLE_TIME_MA : IDLE_TIME;
		for (int i = 0; i < idleTime.length - 1; i++) {
			if ((idleTime[i] + idleTime[i + 1]) / 2 > value) {
				Log.d(TAG, String.format(
						"DEBUG. setIdleTime(%d) - [%d, %d], {%d}", value,
						idleTime[i], idleTime[i + 1], i));
				spinIdleTime.setSelection(i);
				return;
			}
		}
		Log.d(TAG, String.format("DEBUG. setIdleTime(%d) - {%d}", value,
				idleTime.length - 1));
		spinIdleTime.setSelection(idleTime.length - 1);
	}

	private int getAutoPowerOff(){
		return AUTO_POWER_OFF[spinAutoPowerOff.getSelectedItemPosition()];
	}
	private void setAutoPowerOff(int value){
		for (int i = 0; i < AUTO_POWER_OFF.length - 1; i++) {
			if ((AUTO_POWER_OFF[i] + AUTO_POWER_OFF[i + 1]) / 2 > value) {
				Log.d(TAG, String.format(
						"DEBUG. setAutoPowerOff(%d) - [%d, %d], {%d}", value,
						AUTO_POWER_OFF[i], AUTO_POWER_OFF[i + 1], i));
				spinAutoPowerOff.setSelection(i);
				return;
			}
		}
		Log.d(TAG, String.format("DEBUG. setAutoPowerOff(%d) - {%d}", value,
				AUTO_POWER_OFF.length - 1));
		spinAutoPowerOff.setSelection(AUTO_POWER_OFF.length - 1);
	}
	// show LBT channel dialog
	private void showLBTChannelDialog(int value) {
		int state = 0;
		ScrollView root = (ScrollView) TableLayout.inflate(getContext(),
				R.layout.dialog_lbt_channel, null);
		final CheckBox channel[] = new CheckBox[] {
				(CheckBox) root.findViewById(R.id.channel0),
				(CheckBox) root.findViewById(R.id.channel1),
				(CheckBox) root.findViewById(R.id.channel2),
				(CheckBox) root.findViewById(R.id.channel3),
				(CheckBox) root.findViewById(R.id.channel4),
				(CheckBox) root.findViewById(R.id.channel5),
				(CheckBox) root.findViewById(R.id.channel6),
				(CheckBox) root.findViewById(R.id.channel7),
				(CheckBox) root.findViewById(R.id.channel8), };
		AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

		for (int i = 0; i < channel.length; i++) {
			state = (value >> i) & 0x1;
			channel[i].setChecked(state > 0);
		}
		builder.setTitle(getResources().getString(R.string.lbt_channel_title));
		builder.setView(root);
		builder.setPositiveButton(R.string.ok_button_label,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						int state = 0;
						int value = 0;
						for (int i = 0; i < channel.length; i++) {
							state = channel[i].isChecked() ? 1 : 0;
							value += (state << i);
						}
						reader.setLBTChannel(value);
						btnLBTChannel.setEnabled(true);
					}
				});
		builder.setNegativeButton(R.string.cancel_button_label,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						btnLBTChannel.setEnabled(true);
					}
				});
		builder.show();
	}

	// 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);
		}
	}

	// =================================================================
	// Declare Internal Classes
	// =================================================================

	private class InitChecker {
		public static final int POWER = 0;
		public static final int TAG_TYPE = 1;
		public static final int READ_TYPE = 2;
		public static final int INVENTORY_TIME = 3;
		public static final int IDLE_TIME = 4;
		public static final int GLOBAL_BAND = 5;
		public static final int NATIONAL_CODE = 6;
		public static final int SERIAL_NO = 7;
		public static final int USE_SERIAL_NO = 8;
		public boolean init;
		public boolean[] check;

		public InitChecker() {
			init();
		}
		
		public void init() {
			init = false;
			check = new boolean[] { false, false, false, false, false, false,
					false, false, false };
		}
		
		private boolean isInitialized() {
			return !init && check[0] && check[1] && check[2] && check[3]
					&& check[4] && check[5] && check[6] && check[7] && check[8];
		}
	}
	
	private class InitTask extends AsyncTask<Void, Void, Void> {

		private Context context = OptionView.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() {
	}
}
