package com.handheld.LF134KDemo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.handheld.LF134K.LF134KManager;
import com.handheld.apiinstructions.R;
import com.handheld.apiinstructions.SettingActivity;
import com.handheld.apiinstructions.Util;

import cn.pda.serialport.SerialPort;
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.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class LF134KActivity extends Activity implements OnClickListener{
	
	private ListView listID ;
	private Button btnStart ;
	
	private LF134KManager manager ; 
	
	boolean startFlag = false ;
	
	private String tag = "" ;
	
	private Set<String> idSet = new HashSet<String>();
	private List<IDcard> listData = new ArrayList<IDcard>();
	
	private MbaseAdapter adapter ;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			int id = msg.getData().getInt(LF134KManager.KEY_134K_ID) ;
			int country = msg.getData().getInt(LF134KManager.KEY_134K_COUNTRY) ;
			String idString = id+"";
			Log.e("id", idString);
			for (int i = 0; i < 12-idString.length(); i++) {
				idString = "0"+idString;
			}
			String countryString = country+"";
			for (int j = 0; j < 3 - countryString.length(); j++) {
				countryString = "0" +countryString;
			}

			IDcard cardInfo = new IDcard() ;

			if(idSet.isEmpty() || !idSet.contains(idString)){
				idSet.add(idString) ;
				cardInfo.setCount(1);
				cardInfo.setCountryCode(countryString);
				cardInfo.setId(idString);
				listData.add(cardInfo);
			}else{
				int i = 0 ;
				for(; i < listData.size(); i++){
					if(idString.equals(listData.get(i).id)){
						cardInfo.setCount(listData.get(i).count + 1) ;
						cardInfo.setCountryCode(countryString);
						cardInfo.setId(idString);
						listData.set(i, cardInfo) ;
						break ;
					}
				}
				
			}
			Util.play(1, 0) ;
			adapter.notifyDataSetChanged() ;
		};
	} ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_134k) ;
		
		initView();
		Util.initSoundPool(this); 
	}

	private String what = "lf134k";

	private void ConfigInfo(){
		SharedPreferences preference = getSharedPreferences("serialport", Context.MODE_PRIVATE);
		LF134KManager.Port  = preference.getInt(what+"port", SerialPort.com14);
		LF134KManager.BaudRate = preference.getInt(what+"baudrate", SerialPort.baudrate9600);
		LF134KManager.Power = preference.getInt(what+"power", SerialPort.Power_Psam);
		
		String powerString = "";
		switch (LF134KManager.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"+LF134KManager.Port+";Baudrate:"+LF134KManager.BaudRate+";Power:"+powerString);
	}

	private void initView(){
		listID = (ListView) findViewById(R.id.listView_card_id) ;
		btnStart = (Button) findViewById(R.id.button_start) ;
		adapter = new MbaseAdapter() ;
		listID.setAdapter(adapter);
		btnStart.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		ConfigInfo();
		try {
			manager = new LF134KManager() ;
		} catch (SecurityException e) {
			e.printStackTrace();
			Log.e("SecE", e.toString());
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("IOE", e.toString());
		}
		if(manager != null){
			manager.setHandler(handler) ;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (manager!=null) {
			Log.e("", "OnPause");
			manager.close();
		}
	}

	@Override
	protected void onDestroy() {
		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){
			Intent intent = new Intent(LF134KActivity.this, SettingActivity.class);
			intent.putExtra("what", what);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		if(startFlag){
			manager.stopRead() ;
			startFlag = false ;
			btnStart.setText(R.string.start) ;
		}else{
			manager.startRead() ;
			startFlag = true ;
			btnStart.setText(R.string.stop) ;
		}
	}
	
	private class MbaseAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return listData.size();
		}

		@Override
		public Object getItem(int position) {
			return listData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(!listData.isEmpty()){
				ViewHolder holder = null; 
				if(convertView == null){
					LayoutInflater inflater = LayoutInflater.from(LF134KActivity.this) ;
					convertView = inflater.inflate(R.layout.list_item134k, null) ;
					holder = new ViewHolder() ;
					holder.layoutList = (LinearLayout) convertView.findViewById(R.id.layout_list) ;
					holder.tvSn = (TextView) convertView.findViewById(R.id.textView_sn) ;
					holder.tvId = (TextView) convertView.findViewById(R.id.textView_card_id) ;
					holder.tvCount = (TextView) convertView.findViewById(R.id.textView_count) ;
					holder.tvCountry = (TextView) convertView.findViewById(R.id.textView_country) ;
					convertView.setTag(holder) ;
				}else{
					holder = (ViewHolder) convertView.getTag() ;
				}

				IDcard cardInfo = listData.get(position) ;
				holder.tvSn.setText(Integer.valueOf(position+1).toString()) ;
				holder.tvId.setText(Integer.valueOf(cardInfo.getId()).toString());
				holder.tvCount.setText(Integer.valueOf(cardInfo.getCount()).toString());
				holder.tvCountry.setText(Integer.valueOf(cardInfo.getCountryCode()).toString());
			}
			return convertView;
		}
		
		class ViewHolder {
			LinearLayout layoutList ;
			TextView tvSn ;
			TextView tvCountry ;
			TextView tvId ;
			TextView tvCount ;
		}
	}
}
