package com.handheld.LF125KDemo;

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

import android.app.Activity;
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.lf125kdemo1.R;

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);
// auto reread:
//				manager.close();
//				manager = null;
//				Timer timer = new Timer();
//				timer.schedule(new TimerTask() {
//					@Override
//					public void run() {
//						manager = new Lf125KManager();
//						manager.open(mHandler);
//						if (startFlag) manager.start();
//					}
//				},300);
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		getWindow().addFlags(0x80000000);
		setContentView(R.layout.activity_lf);

		initView();
		//new list to save tag data
		listTag = new ArrayList<Tagid>();
		//init sound pool
		Util.initSoundPool(this);
		manager = new Lf125KManager();
			manager.open(mHandler);
	}
	private void ConfigInfo(){
		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+";Power:"+powerString);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ConfigInfo();
		if (manager==null) {
			manager = new Lf125KManager();
			manager.open(mHandler);
			if (startFlag) manager.start();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (manager!=null) {
			manager.close();
			manager = null;
		}
	}

	//
	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) {
				// TODO Auto-generated method stub
				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) {
			switch (v.getId()) {
			//start read
			case R.id.button_startRead_lf:
				if(!startFlag){
					buttonStartRead.setText(R.string.stop);
					manager.start();
					startFlag = true;
				}else{
					buttonStartRead.setText(R.string.start);
					manager.pause();
					startFlag = false;
				}
				
				break;
				//clear
			case R.id.button_clear_lf:
				listTag.removeAll(listTag);
				listView.setAdapter(null);
				break;
			case R.id.button_exit_lf:
				finish();
				break;
			default:
				break;
			}
		}
	}
	
	//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() {
		if (manager!=null)
		manager.close();
		super.onDestroy();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		//Go to SettingActivity
		if(item.getItemId() == R.id.action_settings){
			
		}
		return super.onOptionsItemSelected(item);
	}
}
