package com.bxl.pdftest;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Set;

import com.bxl.BXLConst;
import com.bxl.config.editor.BXLConfigLoader;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import jpos.JposException;
import jpos.POSPrinter;
import jpos.POSPrinterConst;
import jpos.config.JposEntry;

public class MainActivity extends ActionBarActivity
		implements View.OnClickListener, ListDialogFragment.OnClickListener, AdapterView.OnItemClickListener, OnTouchListener {
	
	private static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
	
	
	private static final String DEVICE_ADDRESS_START = " (";
	private static final String DEVICE_ADDRESS_END = ")";

	private final ArrayList<CharSequence> bondedDevices = new ArrayList<>();
	private ArrayAdapter<CharSequence> arrayAdapter;
	
	private String logicalName;
	private BXLConfigLoader bxlConfigLoader;
	private POSPrinter posPrinter;
	private EditText widthEditText;
	private EditText pageEditText;
	private EditText brightnessEditText;
	private RadioGroup alignmentRadioGroup;
	private ListView listView;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		widthEditText = (EditText) findViewById(R.id.editTextWidth);
		widthEditText.setText("300");
		pageEditText = (EditText) findViewById(R.id.editTextPage);
		pageEditText.setText("1");
		brightnessEditText = (EditText) findViewById(R.id.editTextBrightness);
		brightnessEditText.setText("50");
		
		alignmentRadioGroup = (RadioGroup) findViewById(R.id.radioGroupAlignment);
		
		
		setBondedDevices();

		arrayAdapter = new ArrayAdapter<>(this,
				android.R.layout.simple_list_item_single_choice, bondedDevices);
		listView = (ListView) findViewById(R.id.listViewPairedDevices);
		listView.setAdapter(arrayAdapter);

		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		listView.setOnItemClickListener(this);
		listView.setOnTouchListener(this);
		
		findViewById(R.id.buttonOCE).setOnClickListener(this);
		findViewById(R.id.buttonPrintPDF).setOnClickListener(this);
		findViewById(R.id.buttonClose).setOnClickListener(this);
		
		if(bxlConfigLoader == null){
			bxlConfigLoader = new BXLConfigLoader(this);
		}
		if (posPrinter == null) {
			posPrinter = new POSPrinter(this);
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			posPrinter.close();
		} catch (JposException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.buttonOCE:
			try {
				posPrinter.open(logicalName);
				posPrinter.claim(0);
				posPrinter.setDeviceEnabled(true);
			} catch (JposException e) {
				e.printStackTrace();
				
				try {
					posPrinter.close();
				} catch (JposException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
			}
			break;
			
		case R.id.buttonPrintPDF:
			showFileList();
			break;
			
		case R.id.buttonClose:
			try {
				posPrinter.close();
			} catch (JposException e) {
				e.printStackTrace();
				Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}
		
	@Override
	public void onClick(String item) {
		printPDF(item);
	}
	
	private void setBondedDevices() {
		logicalName = null;
		bondedDevices.clear();

		BluetoothAdapter bluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();
		Set<BluetoothDevice> bondedDeviceSet = bluetoothAdapter
				.getBondedDevices();

		for (BluetoothDevice device : bondedDeviceSet) {
			bondedDevices.add(device.getName() + DEVICE_ADDRESS_START
					+ device.getAddress() + DEVICE_ADDRESS_END);
		}

		if (arrayAdapter != null) {
			arrayAdapter.notifyDataSetChanged();
		}
	}
	
		
	private void showFileList() {
		File file = new File(PATH);
		File[] files = file.listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				if (pathname.isDirectory()) {
					return false;
				}
				
				String name = pathname.getName();
				int lastIndex = name.lastIndexOf('.');
				if (lastIndex < 0) {
					return false;
				}
				
				return name.substring(lastIndex).equalsIgnoreCase(".pdf");
			}
		});
		
		if (files != null && files.length > 0) {
			String[] items = new String[files.length];
			for (int i = 0; i < items.length; i++) {
				items[i] = files[i].getAbsolutePath();
			}
			ListDialogFragment.showDialog(getSupportFragmentManager(), "PDF file list", items);
		} else {
			Toast.makeText(getApplicationContext(), "No PDF file", Toast.LENGTH_SHORT).show();
		}
	}
		
	private void printPDF(String fileName) {
		try {
			int width = Integer.valueOf(widthEditText.getText().toString());
			int page = Integer.valueOf(pageEditText.getText().toString());
			int brightness = Integer.valueOf(brightnessEditText.getText().toString());
			
			int alignment = POSPrinterConst.PTR_PDF_LEFT;
			switch (alignmentRadioGroup.getCheckedRadioButtonId()) {
			case R.id.radioCenter:
				alignment = POSPrinterConst.PTR_PDF_CENTER;
				break;
				
			case R.id.radioRight:
				alignment = POSPrinterConst.PTR_PDF_RIGHT;
				break;
			}
			
			posPrinter.printPDF(POSPrinterConst.PTR_S_RECEIPT, fileName, width, alignment, page, brightness);
		} catch (NumberFormatException | JposException e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String device = ((TextView) view).getText().toString();

		logicalName = device.substring(0, device.indexOf(DEVICE_ADDRESS_START));

		String address = device.substring(device.indexOf(DEVICE_ADDRESS_START)
				+ DEVICE_ADDRESS_START.length(),
				device.indexOf(DEVICE_ADDRESS_END));

		try {
			for (Object entry : bxlConfigLoader.getEntries()) {
				JposEntry jposEntry = (JposEntry) entry;
				bxlConfigLoader.removeEntry(jposEntry.getLogicalName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String strProduce = null;
		if(setProductName(logicalName).length() == 0){
			strProduce = logicalName;
		}else{
			strProduce = setProductName(logicalName);
		}
		
		try {
			bxlConfigLoader.addEntry(logicalName,
					BXLConfigLoader.DEVICE_CATEGORY_POS_PRINTER, strProduce,
					BXLConfigLoader.DEVICE_BUS_BLUETOOTH, address);
			
			bxlConfigLoader.saveFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String setProductName(String name){
		String productName = null;
		
		if((logicalName.indexOf("SPP-R200II")>=0)){
			if(logicalName.substring(10, 11).equals("I")){
				productName = BXLConst.SPP_R200III;
			}else{
				productName = BXLConst.SPP_R200II;
			}
		}else if((logicalName.indexOf("SPP-R210")>=0)){
			productName = BXLConst.SPP_R210;
		}else if((logicalName.indexOf("SPP-R310")>=0)){
			productName = BXLConst.SPP_R310;
		}else if((logicalName.indexOf("SPP-R300")>=0)){
			productName = BXLConst.SPP_R300;
		}else if((logicalName.indexOf("SPP-R400")>=0)){
			productName = BXLConst.SPP_R400;
		}
			
		return productName;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_UP)
			listView.requestDisallowInterceptTouchEvent(false);
        else 
        	listView.requestDisallowInterceptTouchEvent(true);
 
        return false;
	}

}
