package com.handheld.Barcode1DDemo;

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

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.handheld.apiinstructions.R;
import com.handheld.apiinstructions.SettingActivity;
import com.handheld.apiinstructions.Util;

public class Barcode1DActivity extends Activity {
	/** UI **/
	private EditText eidtBarCount;
	private Button buttonClear;
	private ListView listViewData;
	private Button buttonScan;
	private Button buttonExit;
	private List<Barcode> listBarcode = new ArrayList<Barcode>();
	private List<Map<String, String>> listMap;
	private SimpleAdapter adapter = null;
	private int fileCount ;
	private String what = "barcode";
	BroadcastReceiver receive;
	private ScanUtil scanUtil;

	private BroadcastReceiver receiverScan = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			byte[] data = intent.getByteArrayExtra("data");
			if (data != null) {
				String barcode = new String(data);
				sortAndadd(listBarcode, barcode);
				addListView();
				eidtBarCount.setText(listBarcode.size() + "");
				Util.play(1, 0);
			}
		}
	};

	private void addListView() {
		listMap = new ArrayList<Map<String, String>>();
		int id = 1;
		for (Barcode barcode : listBarcode) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", id + "");
			map.put("barcode", barcode.getBarcode());
			map.put("count", barcode.getCount() + "");
			listMap.add(map);
		}
		adapter = new SimpleAdapter(this, listMap, R.layout.listview_item,
				new String[] { "id", "barcode", "count", }, new int[] {
						R.id.textView_list_item_id,
						R.id.textView_list_item_barcode,
						R.id.textView_list_item_count });
		listViewData.setAdapter(adapter);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// set HOME key scan
		getWindow().addFlags(0x80000000);
		super.onCreate(savedInstanceState);
		setTitle(R.string._1d_2d_demo);
		setContentView(R.layout.activity_1d2d);
		initView();
		receive  = new FunkeyListener();
		//Registered radio receivers
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.intent.action.FUN_KEY");
		registerReceiver(receive, filter);
		//init sound class
		Util.initSoundPool(this);

		IntentFilter filterScan = new IntentFilter();
		filterScan.addAction("com.rfid.SCAN");
		registerReceiver(receiverScan, filterScan);
		if (scanUtil == null) {
			scanUtil = new ScanUtil(Barcode1DActivity.this);
			scanUtil.setScanMode(0);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (scanUtil == null) {
			scanUtil = new ScanUtil(Barcode1DActivity.this);
			scanUtil.setScanMode(0);
		}
	}

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

	private List<Barcode> sortAndadd(List<Barcode> list, String barcode) {
		Barcode goods = new Barcode();
		goods.setBarcode(barcode);
		int temp = 1;
		if (list == null || list.size() == 0) { 
			goods.setCount(temp);
			list.add(goods);
			return list;
		}
		
		for (int i = 0; i < list.size(); i++) { 
			if (barcode.equals(list.get(i).getBarcode())) {
				temp = list.get(i).getCount() + temp;
				goods.setCount(temp);
				for (int j = i; j > 0; j--) {
					list.set(j, list.get(j - 1)); 
				}
				list.set(0, goods);
				return list;
			}
		}

		Barcode lastgoods = list.get(list.size() - 1); 
		for (int j = list.size() - 1; j >= 0; j--) {
			if (j == 0) {
				goods.setCount(temp);
				list.set(j, goods); 
			} else {
				list.set(j, list.get(j - 1));
			}

		}
		list.add(lastgoods);
		return list;
	}

	long exitSytemTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == 131 || keyCode == 132 || keyCode == 133 || keyCode == 134|| keyCode == 135 || keyCode == 136){
			scanUtil.setTimeout("5000");
			scanUtil.scan();
		}

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (System.currentTimeMillis() - exitSytemTime > 2000) {
				Toast.makeText(getApplicationContext(), R.string.exitSystem,
						Toast.LENGTH_SHORT).show();
				exitSytemTime = System.currentTimeMillis();
				return true;
			} else {
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// Unregister receiver
		unregisterReceiver(receive);
		unregisterReceiver(receiverScan);
		fileCount++;
		SharedPreferences shared = this.getPreferences(Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = shared.edit();
		editor.putInt("fileCount", fileCount);
		editor.apply();
		scanUtil.close();
		super.onDestroy();
	}

	private void initView() {
		eidtBarCount = (EditText) findViewById(R.id.editText_barcode_count);
		buttonClear = (Button) findViewById(R.id.button_clear);
		listViewData = (ListView) findViewById(R.id.listView_data_list);
		buttonScan = (Button) findViewById(R.id.button_scan);
		buttonExit = (Button) findViewById(R.id.button_exit);
		buttonScan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				scanUtil.setTimeout("5000");
				scanUtil.scan();; // second ; needed for scan to work
			}
		});
		
		buttonClear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				eidtBarCount.setText("");
				listBarcode.removeAll(listBarcode);
				listViewData.setAdapter(null);
			}
		});
		
		buttonExit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private class FunkeyListener extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			boolean defaultdown=false;
	        int keycode = intent.getIntExtra("keycode", 0);    
	        boolean keydown = intent.getBooleanExtra("keydown", defaultdown);      
	        if (keydown){
	        	if (keycode == 131 || keycode == 132 || keycode == 133 || keycode == 134|| keycode == 135 || keycode == 136){
					scanUtil.scan();;
				}
	        } else {
				scanUtil.stopScan();
			}
		}
	}

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

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

}
