package com.naz.sdkdemo.activity;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.naz.sdkdemo.R;
import com.naz.sdkdemo.base.BaseActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import android_serialport_api.SerialPortFinder;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.stick.AbsStickPackageHelper;
import tp.xmaihh.serialport.utils.ByteUtil;

public class TestActivity extends BaseActivity {
   private SerialHelper serialHelper;
   private boolean isHexType = true;
   private boolean isOr = false;

   TextView receiveTxt;

   private Handler mHandler = new Handler(new Handler.Callback() {
      @Override
      public boolean handleMessage(Message msg) {
         ComBean comBean = (ComBean) msg.obj;
         String time = comBean.sRecTime;
         String rxText;
         rxText = new String(comBean.bRec);
         if (isHexType) {
            //转成十六进制数据
            rxText = ByteUtil.ByteArrToHex(comBean.bRec);
         }
         String text = "Rx-> " + time + ": " + rxText + "\r" + "\n";
         receiveTxt.setText(text);
         return false;
      }
   });

   @Override
   protected int getLayoutResId() {
      return R.layout.activity_test;
   }

   @Override
   protected void initView() {
      findViewById(R.id.open).setOnClickListener(this);
      findViewById(R.id.close).setOnClickListener(this);
      findViewById(R.id.send).setOnClickListener(this);
      findViewById(R.id.send2).setOnClickListener(this);

      receiveTxt = findViewById(R.id.receive_content);

      SerialPortFinder finder = new SerialPortFinder();
//      Toast.makeText(this, "device---"+(finder.getAllDevices()), Toast.LENGTH_SHORT).show();
//      Toast.makeText(this, "path---"+(finder.getAllDevicesPath()), Toast.LENGTH_SHORT).show();
      TextView portTxt = findViewById(R.id.port);
      TextView deviceTxt = findViewById(R.id.device);
      if (finder.getAllDevicesPath().length>0){
         StringBuilder path = new StringBuilder();
         for (int i = 0; i < finder.getAllDevicesPath().length; i++) {
            path.append(finder.getAllDevicesPath()[i]).append(", ");
         }
         portTxt.setText(path);
      }
      if (finder.getAllDevices().length>0){
         StringBuilder device = new StringBuilder();
         for (int i = 0; i < finder.getAllDevices().length; i++) {
            device.append(finder.getAllDevices()[i]).append(", ");
         }
         deviceTxt.setText(device);
      }

      initSerialConfig();

      Log.e("-------->",""+(getCRC(new byte[]{0x01, 0x03, 0x00, 0x00, 0x00, 0x01}))[0]);
      Log.e("-------->",""+(getCRC(new byte[]{0x01, 0x03, 0x00, 0x00, 0x00, 0x01}))[1]);
   }

   @Override
   public void onClick(View v) {
      if (v.getId() == R.id.open){
         if (serialHelper.isOpen()) {
            Toast.makeText(this, "串口已经打开", Toast.LENGTH_SHORT).show();
            return;
         }
         try {
            serialHelper.open();
         } catch (IOException e) {
            e.printStackTrace();
         }
         Toast.makeText(this, "串口打开成功", Toast.LENGTH_SHORT).show();
      }else if (v.getId() == R.id.close){
         if (serialHelper.isOpen()) {
            serialHelper.close();
            Toast.makeText(this, "串口已经关闭", Toast.LENGTH_SHORT).show();
         }
      }else if (v.getId() == R.id.send){
         if (!serialHelper.isOpen()) {
            Toast.makeText(this, "串口没打开 发送失败", Toast.LENGTH_SHORT).show();
            return;
         }
         String sendContent;
         if (isOr){
            sendContent = "0000";
         }else {
            sendContent = "0001";
         }
         isOr = !isOr;
//         if (isHexType) {
//            serialHelper.sendHex(sendContent);
//         } else {
//            serialHelper.sendTxt(sendContent);
//         }
         serialHelper.send(new byte[]{0x01, 0x03, 0x00, 0x00, 0x00, 0x01, (byte) 0x84, (byte) 0x0A});
      }else if (v.getId() == R.id.send2){
         if (!serialHelper.isOpen()) {
            Toast.makeText(this, "串口没打开 发送失败", Toast.LENGTH_SHORT).show();
            return;
         }
         String sendContent;
         if (isOr){
            sendContent = "0000";
         }else {
            sendContent = "0001";
         }
         isOr = !isOr;
//         if (isHexType) {
//            serialHelper.sendHex(sendContent);
//         } else {
//            serialHelper.sendTxt(sendContent);
//         }
         serialHelper.send(new byte[]{0x01, 0x06, 0x00, 0x00, 0x00, 0x01, (byte) 0x48, (byte) 0x0A});
      }
   }

   private void initSerialConfig() {
      //初始化SerialHelper对象，设定串口名称和波特率（此处为接收扫码数据）
      serialHelper = new SerialHelper("/dev/ttyACM0", 19200) {
         @Override
         protected void onDataReceived(ComBean paramComBean) {
//            receiveTxt.setText("onDataReceived"+paramComBean.toString());
            Message message = mHandler.obtainMessage();
            message.obj = paramComBean;
            Log.e("TAG", "onDataReceived: " + message.obj);
//            Toast.makeText(TestActivity.this, "onDataReceived: " + message.obj, Toast.LENGTH_SHORT).show();
            mHandler.sendMessage(message);
         }
      };

//      /*
//       * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
//       * 我这里重新设定一个自适应数据位数的
//       */
//      serialHelper.setStickPackageHelper(new AbsStickPackageHelper() {
//         @Override
//         public byte[] execute(InputStream is) {
//            try {
//               int available = is.available();
//               if (available > 0) {
//                  byte[] buffer = new byte[available];
//                  int size = is.read(buffer);
//                  if (size > 0) {
//                     return buffer;
//                  }
//               } else {
//                  SystemClock.sleep(50);
//               }
//
//            } catch (IOException e) {
//               e.printStackTrace();
//            }
//            return null;
//         }
//      });

   }

   /**
    * 计算CRC16校验码
    *
    * @param bytes 需要计算的字节数组
    */
   public byte[] getCRC(byte[] bytes) {
      int CRC=0x0000ffff;
      int POLYNOMIAL=0x0000a001;
      int i,j;
      for(i=0;i<bytes.length;i++){
         CRC^=((int)bytes[i]&0x000000ff);
         for(j=0;j<8;j++){
            if((CRC&0x00000001)!=0){
               CRC>>=1;
               CRC^=POLYNOMIAL;
            }else{
               CRC>>=1;
            }
         }
      }
      byte lowByte = (byte) (CRC>>>8&0x000000ff);
      byte highByte = (byte) (CRC&0x000000ff);
      byte[] array = new byte[2];
      array[0] = lowByte;
      array[1] = highByte;
      return array;
//      return ByteArray(0).plus(highByte).plus(lowByte);
//      return Integer.toHexString(CRC);
   }
}
