package com.sage.usbhelper;


import android.hardware.usb.UsbDevice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.sage.usbhelper.lib.USBHelper;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnFindAll, btnOpenOne, btnSend, btnRead;
    private TextView tvContent;

    public TextView tvPrintf;

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

        btnFindAll = findViewById(R.id.btn_findAll);
        btnFindAll.setOnClickListener(this);
        btnOpenOne = findViewById(R.id.btn_openOne);
        btnOpenOne.setOnClickListener(this);

        btnSend = findViewById(R.id.btn_send);
        btnSend.setOnClickListener(this);

        btnRead = findViewById(R.id.btn_receive);
        btnRead.setOnClickListener(this);

        tvContent = findViewById(R.id.tv_content);
        String str = "nico hid test";
        tvContent.setText(str);

        // init USBHelper debug printf
        tvPrintf = findViewById(R.id.tv_printf);
        USBHelper.getInstance(this).DebugInitial(tvPrintf);

        USBHelper.getInstance(this).scanInit();

        deviceOK = 0;

      /*  new Thread() {
            //@Override
            int cnt = 0;
            public void run() {
                while(true){
                    // TODO
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String str = "read:" + cnt;
                            tvContent.setText(str);
                            cnt ++;
                        }
                    });
                    try{
                        Thread.sleep(1000);
                    }catch(Exception e){
                    }
                }
            }
        }.start();*/
    }



    //@Override
    protected int scannerCustomerDataSend(){
        int statue =0;
      String str = "scannerCustomerDataSend\n";
        tvContent.setText(str);

       // byte buffer[] = new byte[33];
        //String auth="pc_get_auth";
        String auth="^_^SCAN.";
        byte[] buffer = auth.getBytes();
        statue = USBHelper.getInstance(this).sendData(buffer);

        str = auth + "sendData ret:"+statue;
        str += buffer.toString();
        tvContent.setText(str);

        return statue;
    }

    protected void CustomerDataRead(final USBHelper Hepler){
        new Thread(new Runnable(){
            //@Override
            int cnt = 0;
            String sendString = "";
            byte[] buffer = new byte[33];
            public void run() {
                //while(deviceOK==1){
                while(true){
                    // TODO
                  //int status= USBHelper.getInstance(this).readData(buffer, 32, 2000);
                    final int status= Hepler.readData(buffer, 32, 2000);
                    if(status == 10002 || status==-1){
                        System.out.println("timer out!!");
                        sendString = "";
                    }else{
                        System.out.println("\nread data:" +status);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sendString += new String(buffer, "UTF-8");
                            }catch (Exception e) {
                            }
                            tvContent.setText(sendString);

                            /*sendString += "read:" + cnt;
                            tvContent.setText(sendString);
                            cnt ++;*/
                        }
                    });

                    try{
                        Thread.sleep(200);
                    }catch(Exception e){
                    }
                }

                //System.out.println("out thread !");
            }
        }).start();
    }


    int readcnt=0;
    protected void scannerCustomerDataRead(){
        byte[] buffer = new byte[33];
       // while(true)
        {
            String str = "scannerCustomerDataRead\n";
            tvContent.setText(str);

            //String auth="pc_get_auth";
            // byte[] buffer = auth.getBytes();
            readcnt ++;
            int status= USBHelper.getInstance(this).readData(buffer, 32, 0);

            System.out.println(Arrays.toString(buffer));
            str += "DataRead cnt:" + readcnt;
            // str += System.out.println(Arrays.toString(buffer));
            tvContent.setText(str);

            String sendString = "";
            try {
                sendString = new String(buffer, "UTF-8");
            }catch (Exception e) {

            }
            tvContent.setText(sendString);

            try {
                wait(1000);
            }catch (Exception e) {
            }

            runOnUiThread(new Runnable() {
                //@Override
                int cnt;
                public void run() {
                    String str = "read:n" ;
                    tvContent.setText(str);
                    cnt ++;
               /* String sendString = "";
                try {
                    sendString = new String(buffer, "UTF-8");
                }catch (Exception e) {

                }
                tvContent.setText(sendString);*/
                }
            });

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_findAll:
                /*List<UsbDevice> list = USBHelper.getInstance(this).getUsbDevices();
                String str = "";
                for (UsbDevice device : list) {
                    str = str + device.getDeviceName() + "\n";
                }
                if (TextUtils.isEmpty(str)) str = "当前设备没有接入USB设备";
                tvContent.setText(str);*/
                break;
            case R.id.btn_openOne:
                List<UsbDevice> list2 = USBHelper.getInstance(this).getUsbDevices();
                for (UsbDevice device : list2) {
                    //int statue = USBHelper.getInstance(this).connection(device.getVendorId(), device.getProductId());
                    int statue = USBHelper.getInstance(this).connection(0x0525, 0x7a42);
                    tvContent.setText("连接状态：" + statue);
                    if(statue==0) deviceOK = 1;
                }
                break;

            case R.id.btn_send:
                scannerCustomerDataSend();
                break;

            case R.id.btn_receive:
               // scannerCustomerDataRead();
                CustomerDataRead(USBHelper.getInstance(this));

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        USBHelper.getInstance(this).close();
    }
}
