/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.example.uartscantest;

import com.tool.ScanActivity;
import com.tool.SerialPortActivity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ConsoleActivity extends Activity {

	TextView status;
    TextView mymsg;
    Button start;
    Button stop;
	EditText mReception;
	ScanActivity Tsexample;
	static int DecodeCnt = 0;
	private static final String TAG = "ConsoleActivity";
	public boolean ExitFlag = false;
    public boolean RetryScan = false;
    public boolean BusyFlag = false;
    //消息
    public final static int HANDLER_SCAN_STATUS = 1;
    public final static int HANDLER_SCAN_DEC = 2;
    public final static int HANDLER_SCAN_TEXT = 4;
    public final static int HANDLER_SCAN_CLEAR = 5;

    private String strUartName;
    private int uiBaudrate;
    static int uiDecodeCnt = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
        byte ucrnmode;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scan);
		
		status = (TextView) findViewById(R.id.device_status);
        mymsg = (TextView) findViewById(R.id.device_msg);
        start = (Button) findViewById(R.id.start_scan);
        stop = (Button) findViewById(R.id.stop_scan);

        Tsexample = new ScanActivity();;
        getSerialPort();
        Log.w(TAG,"uart:" + strUartName +"baudrate:"+ uiBaudrate);

        ScanActivity.TsDataCallBack tsdatacallback = new ScanActivity.TsDataCallBack() {
            @Override
            public int ts_get_data_fun(byte[] pParam, byte[] pbuf, int uiBufLen) {
                byte[] decode = new byte[uiBufLen];   //数据域
                System.arraycopy(pbuf, 0, decode, 0, uiBufLen);
                ScanMsg(HANDLER_SCAN_DEC, 0, 0, new String(decode));

                System.out.printf("[%03d]len:%d, buf:",++uiDecodeCnt, uiBufLen);
                for (byte b : pbuf) {
                    System.out.printf("%c", b);
                }
                System.out.println();
                return 0;
            }
        };

        ScanActivity.TsStateCallBack tsstatecallback = new ScanActivity.TsStateCallBack() {
            @Override
            public int ts_scan_state_fun(byte[] pParam,byte ucState) {
                String stbuf;
                byte[] ucBufTemp;
                byte[] ucBufTemp1;
                int iRet;
                System.out.printf("状态=%d\r\n",ucState);
                if(ucState == 1)
                {
                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_product_name(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, product name:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, product name:%s\r\n",iRet,"null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_product_id(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, product id:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, product id:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_product_date(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, product date:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, product date:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_custom_name(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, custom name:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, custom name:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_custom_id(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, custom id:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, custom id:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_custom_date(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, custom date:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, custom date:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_firmware_version(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, firmware version:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, firmware version:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_hardware_version(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, hardware version:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, hardware version:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_complex_sn(ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, COMPLEX SN:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, COMPLEX SN:%s\r\n", iRet, "null");
                    }
                }
                return 0;
            }
        };

        Tsexample.ts_scan_get_data_fun_register(null, tsdatacallback);
        Tsexample.ts_scan_state_fun_register(null, tsstatecallback);

        System.out.print("hello c++ hidpos scan demo\r\n");
        /**获取扫描模块版本号**/
        System.out.printf("scan dll ver:%s [%d]\r\n", Tsexample.ts_scan_get_version(), Tsexample.ts_scan_get_product_type());
        ScanMsg(HANDLER_SCAN_TEXT,0,0,"版本:"+Tsexample.ts_scan_get_version()+"模块类别:" + Tsexample.ts_scan_get_product_type());
        /**设置RS485 组网模式 1为组网模式，0为普通模式**/
        ucrnmode = 0;
        Tsexample.ts_scan_set_rs485_net_mode(ucrnmode);
        if(1 == ucrnmode)
            System.out.print("set rs485 net mode\r\n");
        else
            System.out.print("set nor mode\r\n");

        Tsexample.ts_scan_init();

        Log.w(TAG, "ScanActivity");
        Tsexample.ts_scan_uart_findPorts();

        try {
            int iRet = Tsexample.ts_scan_uart_open(strUartName, uiBaudrate);
            if(-1 == iRet)
                Log.w(TAG, "ts_scan_uart_open FAIL");
            else
                Log.w(TAG, "ts_scan_uart_open succ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ExitFlag = true;

		start.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View view) {
	            new Thread(new StartDecodeRunnable()).start();
	        }
	    });

	    stop.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View view) {
	            new Thread(new StopDecodeRunnable()).start();
	        }
	    });
	}

    public int getSerialPort(){
        String shartpath = getPackageName() + "_preferences";

        /* Read serial port parameters */
        SharedPreferences sp = getSharedPreferences(shartpath, MODE_PRIVATE);
        String path = sp.getString("DEVICE", "");
        int baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));

        /* Check parameters */
        if ( (path.length() <= 0) || (baudrate == -1)) {
            return -1;
            //throw new InvalidParameterException();
        }

        strUartName = path;
        uiBaudrate = baudrate;
        return 0;
    }

	private class StartDecodeRunnable implements Runnable{
        @Override
        public void run() {
            int iRet;
            // TODO Auto-generated method stub
            Log.w(TAG, "StartDecodeRunnable");
            while(BusyFlag){Sleep(10);};
            BusyFlag = true;
            //ScanDevice curDevice = namesList.get(selectPosition);
            try {
                iRet = Tsexample.ts_scan_decode_start();
                if(iRet == -1)
                    ScanMsg(HANDLER_SCAN_TEXT, 0, 0, "开启失败");
                else
                    ScanMsg(HANDLER_SCAN_TEXT, 0, 0, "开启成功");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            BusyFlag = false;
        }
    }
    
    private class StopDecodeRunnable implements Runnable{
        @Override
        public void run() {
            int iRet;
            while(BusyFlag){Sleep(10);};
            BusyFlag = true;
            //ScanDevice curDevice = namesList.get(selectPosition);
            try {
                iRet = Tsexample.ts_scan_decode_stop();
                if(iRet == -1)
                    ScanMsg(HANDLER_SCAN_TEXT, 0, 0, "关闭失败");
                else
                    ScanMsg(HANDLER_SCAN_TEXT, 0, 0, "关闭成功");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            BusyFlag = false;
        }
    }

	protected void onDataReceived(final byte[] buffer, final int size) {
		runOnUiThread(new Runnable() {
			public void run() {
				if (mReception != null) {
					mReception.append(new String(buffer, 0, size));
				}
			}
		});
	}
	
	private void Sleep(long ms)
    {
        try {Thread.sleep(ms);} catch (InterruptedException e) {e.printStackTrace();}
    }

    private void ScanMsg(int mode, int type, int status, Object value)
    {
        Message msg = new Message();
        msg.what = mode;
        msg.arg1 = type;
        msg.arg2 = status;
        msg.obj = value;
        myHandler.sendMessage(msg);
    }
	
	Handler myHandler = new Handler()
    {
        public void handleMessage(Message msg)  
        {  
            int deviceId;
            deviceId = msg.arg1;
            switch(msg.what)  
            {
                case HANDLER_SCAN_STATUS:
                    //AddDevice(deviceId);
                    //ChangeDeviceStatus(deviceId, ScanDevice.DEVICE_CONNECT);
                    break;
                case HANDLER_SCAN_DEC:
                    RetryScan= true;
                    Log.w(TAG, "HANDLER_SCAN_DEC");
                    mymsg.setText("[" + (++DecodeCnt) + "]" + "解码数据：" + (String)msg.obj);
                    break;

                case HANDLER_SCAN_TEXT:
                    status.setText((String)msg.obj);
                    break;
                case HANDLER_SCAN_CLEAR:
                    //selectPosition = -1;
                    //ClearDeviceList();
                    //ChangeDeviceStatus(deviceId, ScanDevice.DEVICE_CONNECT);
                    break;
            }
        }
    };
    
    @Override
	protected void onDestroy() {
    	if(ExitFlag) {
            try {
                Tsexample.ts_scan_uart_close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    	ExitFlag = false;
    	super.onDestroy();
	}
}
