package com.naz.sdkdemo.helper;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import androidx.annotation.NonNull;

public class SerialIPManager {
    private Handler mHandler;
    private Socket socket;
    InputStream inputStream;//获取输入流
    byte[] RevBuff = new byte[1460];//缓存数据
    OutputStream outputStream;
    private ConnectCallBack mConnectCallBack;

    public void init(){
        mHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.e("------->","-------->handleMessage="+msg.toString());
                switch (msg.what){
                    case 0:
                        if (mConnectCallBack!=null){
                            mConnectCallBack.connectResult(0);
                        }
                        break;
                    case 1:
                        if (mConnectCallBack!=null){
                            mConnectCallBack.connectResult(1);
                        }
                        break;
                    case 3:
                        byte[] buffer = new byte[msg.arg1];
                        Log.e("------->","-------->buffer="+buffer.length);
                        System.arraycopy((byte[])msg.obj, 0, buffer, 0, msg.arg1);
                        if (mConnectCallBack!=null){
                            mConnectCallBack.receiveData(new String(buffer));
                        }
                        break;
                    default: break;
                }

            }
        };

    }

    public void connect(String host, int port, ConnectCallBack callBack){
        Log.e("------->","-------->connect");
        mConnectCallBack = callBack;
        if (socket != null && socket.isConnected())
            return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = mHandler.obtainMessage();
                try{
                    socket = new Socket(host, port);
                    if(socket.isConnected()){
                        Log.e("------->","-------->socket.isConnected()");
                        msg.what = 1;//设置消息变量的 what 变量值 为1
                        inputStream = socket.getInputStream();
                        outputStream = socket.getOutputStream();
                        receiverMethod();
                    }
                }catch (Exception e){
                    msg.what = 0;//设置消息变量的 what 变量值 为0
                }
                mHandler.sendMessage(msg);//插入消息队列
            }
        }).start();
    }

    private void receiverMethod() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (socket!= null && socket.isConnected()){
                    try{
                        int Len = inputStream.read(RevBuff);//获取数据
                        if(Len!=-1){
                            Message msg = mHandler.obtainMessage();//从消息队列拉取个消息变量
                            msg.what = 3;//设置消息变量的 what 变量值 为3
                            msg.arg1 = Len;//接收的数据个数
                            msg.obj = RevBuff;//传递数据
                            mHandler.sendMessage(msg);//插入消息队列
                            Log.e("------------>","-------->what="+msg.what);
                            Log.e("------------>","-------->arg1="+msg.arg1);
                            Log.e("------------>","-------->obj="+msg.obj);
                        }
                        else{//连接异常断开
                            Message msg = mHandler.obtainMessage();//从消息队列拉取个消息变量
                            msg.what = 0;//设置消息变量的 what 变量值 为0
                            mHandler.sendMessage(msg);//插入消息队列
                            break;
                        }
                    }catch (Exception e){//连接异常断开
                        if (isClose)
                            return;
                        Message msg = mHandler.obtainMessage();//从消息队列拉取个消息变量
                        msg.what = 0;//设置消息变量的 what 变量值 为0
                        mHandler.sendMessage(msg);//插入消息队列
                        break;
                    }
                }

            }
        }).start();
    }

    private void scanSerial(String serial){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    outputStream.write(serial.getBytes());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
    boolean isClose = false;
    public void close(CloseCallBack callBack){
        try{
            isClose = true;
            mHandler.removeCallbacksAndMessages(null);
            socket.close();
            mHandler=null;
            inputStream.close();
            outputStream.close();
            callBack.closeResult(1);
        }catch (Exception e){
            callBack.closeResult(0);
        }
    }

    public interface ConnectCallBack{
        void connectResult(int code);//1成功 0失败
        void receiveData(String data);
    }

    public interface CloseCallBack{
        void closeResult(int code);//1成功 0失败
    }
}
