package com.handheld.LF125KDemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import cn.pda.serialport.SerialPort;

import com.handheld.LF125K.Lf125KManager;
import com.handheld.apiinstructions.R;
import com.handheld.apiinstructions.SettingActivity;
import com.handheld.apiinstructions.Util;

public class LF125KActivity extends Activity {

	private Button buttonStartRead;
	private Button buttonClear;
	private Button buttonExit;
	private ListView listView;
	private List<Tagid> listTag;
	private List<Map<String, String>> listMap;
	private Lf125KManager manager;
	private CheckBox checkbox_hex;

	//Receive data and update UI by handler
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if (msg.what == manager.LF) {
				Bundle bundle = msg.getData();
				String data = bundle.getString("data");
				updateUI(data);
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lf);
		manager = new Lf125KManager();
		initView();
		//new list to save tag data
		listTag = new ArrayList<Tagid>();
		//init sound pool
		Util.initSoundPool(this);
	}

	private void ConfigInfo(){
		SharedPreferences preference = getSharedPreferences("serialport", Context.MODE_PRIVATE);
		Lf125KManager.Port  = preference.getInt(what+"port", SerialPort.com14);
		Lf125KManager.BaudRate = preference.getInt(what+"baudrate", SerialPort.baudrate9600);
		Lf125KManager.Power = preference.getInt(what+"power", SerialPort.Power_Psam);
		
		String powerString = "";
		switch (Lf125KManager.Power) {
		case SerialPort.Power_3v3:
			powerString = "power_3V3";
			break;
		case SerialPort.Power_5v:
			powerString = "power_5V";
			break;
		case SerialPort.Power_Scaner: 
			powerString = "scan_power";
			break;
		case SerialPort.Power_Psam:
			powerString = "psam_power";
			break;
		case SerialPort.Power_Rfid:
			powerString = "rfid_power";
			break;
		default:
			break;
		}
		((TextView) findViewById(R.id.textview_title_config)).setText("Port:com"+Lf125KManager.Port+";Baudrate:"+Lf125KManager.BaudRate+";Power:"+powerString);
	}

	@Override
	protected void onResume() {
		super.onResume();
		ConfigInfo();
		manager.Open(mHandler);
	}

	private void initView() {
		buttonStartRead = (Button) findViewById(R.id.button_startRead_lf);
		buttonClear = (Button) findViewById(R.id.button_clear_lf);
		buttonExit = (Button) findViewById(R.id.button_exit_lf);
		listView = (ListView) findViewById(R.id.listView1_lf);
		buttonStartRead.setOnClickListener(new MyonClick());
		buttonClear.setOnClickListener(new MyonClick());
		buttonExit.setOnClickListener(new MyonClick());
		checkbox_hex = (CheckBox) findViewById(R.id.checkbox_hex);
		checkbox_hex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean ischecked) {
				if (ischecked) {
					Lf125KManager.Hex = true;
				}else {
					Lf125KManager.Hex = false;
				}
			}
		});
	}

	private boolean startFlag = false;

	//click listener
	private class MyonClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			if (v.getId() == R.id.button_startRead_lf) {//start read
				if (!startFlag) {
					buttonStartRead.setText(R.string.stop);
					manager.Start();
					startFlag = true;
				} else {
					buttonStartRead.setText(R.string.start);
					manager.Pause();
					startFlag = false;
				}
			} else if (v.getId() == R.id.button_clear_lf) {//clear
				listTag.removeAll(listTag);
				listView.setAdapter(null);
			} else if (v.getId() == R.id.button_exit_lf) {
				finish();
			}
		}
	}
	
	//add to list
	private List<Tagid> addToList(List<Tagid> list, String tagId){
		Tagid tag = new Tagid();
		tag.setTag(tagId);
		int temp = 1;
		if(list == null || list.size() == 0){  //add this id for the first time
			tag.setCount(temp);
			list.add(tag);
			return list;
		}
		//the list contain this epc 
		for(int i = 0; i < list.size(); i++){  //list
			if(tagId.equals(list.get(i).getTag())){ 
				temp = list.get(i).getCount() + temp;
				tag.setCount(temp);
				for(int j = i; j > 0 ; j--){
					list.set(j, list.get(j-1));  
				}
				list.set(0, tag);
				return list;
			}
		}

		Tagid lastTagid = list.get(list.size() - 1);
		for(int j = list.size() - 1; j >= 0 ; j--){
			if(j == 0){
				tag.setCount(temp); 
				list.set(j, tag);
			}else{
				list.set(j, list.get(j - 1));
			}
		}
		list.add(lastTagid);
		
		return list;
	}
	
	//update UI
	private void updateUI(final String tagId){
		
	runOnUiThread(new Runnable() {
		@Override
		public void run() {
			List<Tagid> listst = addToList(listTag, tagId);
			listMap = new ArrayList<Map<String,String>>();
				for (Tagid tag : listst) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("id", tag.getId() + "");
					map.put("tag", tag.getTag()+"");
					map.put("count", tag.getCount() + "");
					listMap.add(map);
				}
				
			ListAdapter adapter = new SimpleAdapter(LF125KActivity.this, listMap, R.layout.listview_item,
					new String[] { "id", "tag", "count", }, new int[] {
							R.id.textView_list_item_id,
							R.id.textView_list_item_barcode,
							R.id.textView_list_item_count });
			listView.setAdapter(adapter);
			Util.play(1, 0);
			}
		});
	}

	@Override
	protected void onDestroy() {
		manager.Close();
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	private String what = "lf125k";
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//Go to SettingActivity
		if(item.getItemId() == R.id.action_settings){
			Intent intent = new Intent(LF125KActivity.this, SettingActivity.class);
			intent.putExtra("what", what);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}
}
