package com.nlscan.android.usbserialtest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.nlscan.android.usbserialdemo.UsbService;

public class MainActivity extends AppCompatActivity {

    TextView status;
    TextView mymsg;
    Button start;
    Button stop;

    static int DecodeCnt = 0;

    private static final String TAG = "MainActivity";
    private int selectPosition = -1;

    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 UsbService Tsexample;
    static int uiDecodeCnt = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        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 UsbService(this);;

        UsbService.TsDataCallBack tsdatacallback = new UsbService.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;
            }
        };

        UsbService.TsStateCallBack tsstatecallback = new UsbService.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)
                {
                    ScanMsg(HANDLER_SCAN_TEXT, 0, 0, "设备连接成功");
                    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");
                    }
                }
                else
                {
                    ScanMsg(HANDLER_SCAN_TEXT, 0, 0, "设备断开连接");
                }
                return 0;
            }
        };

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

        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,"版本:V"+Tsexample.ts_scan_get_version()+" 模块类别:" + Tsexample.ts_scan_get_product_type());

        Tsexample.ts_scan_init();

        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();
            }
        });
    }
    private void Sleep(long ms)
    {
        try {Thread.sleep(ms);} catch (InterruptedException e) {e.printStackTrace();}
    }

    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;
        }
    }

    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;
            }
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if( (keyCode == KeyEvent.KEYCODE_BACK ) ||  (keyCode == KeyEvent.KEYCODE_HOME ) )
        {
            System.exit(0);
        }
        return false;
    }
}