package com.example.writeepc;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;

import com.example.writeepc.base.BaseActivity;
import com.example.writeepc.databinding.ActivitySocketBinding;
import com.example.writeepc.utils.SharedPreferencesUtils;
import com.google.android.material.snackbar.Snackbar;
import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;

import java.nio.charset.Charset;

public class SocketActivity extends BaseActivity {
    private ActivitySocketBinding binding;
    private View view;
    private IConnectionManager manager;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:

                    Snackbar.make(view, "连接成功", Snackbar.LENGTH_LONG).show();
                    break;

                case 2:
                    String errorInfo = msg.getData().getString("data");
                    Snackbar.make(view, "连接失败，原因是" + errorInfo, Snackbar.LENGTH_LONG).show();
                    break;

                case 3:

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_socket);
        initUHFRManager();
        binding.socketSan.setOnClickListener(v -> /*readEPC(12)*/{
            readEPC(24);
            // manager.send(new TestSendData(binding.socketEpc.getText().toString()));
        });

        view = binding.getRoot();
        PopupMenu popupMenu = new PopupMenu(this, binding.socketTitle);
        getMenuInflater().inflate(R.menu.socket_menu, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(item -> {
            showDialog();
            return false;
        });
        binding.socketTitle.setOnClickListener(v -> popupMenu.show());
        String ipAddr = SharedPreferencesUtils.getstring("ip", null);
        if (ipAddr == null) {
            showDialog();
        } else {
            startscoket();
        }
    }
    //显示输入弹窗
    private void showDialog() {
        if (manager != null && manager.isConnect()) {
            manager.disconnect();
        }
        EditText editText = new EditText(this);
        editText.setLines(1);
        editText.setMaxLines(1);
        String ipAddr = SharedPreferencesUtils.getstring("ip", null);
        editText.setText(ipAddr);
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("输入IP地址：端口号").setView(editText).setNeutralButton("取消", null)
                .setPositiveButton("保存", (dialog1, which) -> {
                    String ip = editText.getText().toString().trim();
                    SharedPreferencesUtils.putstring("ip", ip);
                    startscoket();
                }).create().show();
    }

    // RFID返回结果
    @Override
    protected void readTidReault(boolean readState, String result, byte[] rdata) {
        super.readTidReault(readState, result, rdata);
        binding.socketEpc.setText(result);
        manager.send(new TestSendData(result));
    }

    // 连接服务端
    private void startscoket() {
        String IP = SharedPreferencesUtils.getstring("ip", "");
        try {
            String[] split = IP.split(":");
            ConnectionInfo info = new ConnectionInfo(split[0], Integer.parseInt(split[1]));
            manager = OkSocket.open(info);
        } catch (ArrayIndexOutOfBoundsException e) {
            Toast.makeText(this, "IP和端口号异常", Toast.LENGTH_SHORT).show();
            showDialog();
            return;
        }

        // 连接回调
        manager.registerReceiver(new SocketActionAdapter() {
            @Override
            public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
                handler.sendEmptyMessage(1);
            }

            @Override
            public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
                String str = new String(data.getBodyBytes(), Charset.forName("utf-8"));
                Log.d("tag", "客户端读取数据回调" + str);

                super.onSocketReadResponse(info, action, data);

            }
            // 发送状态
            @Override
            public void onSocketWriteResponse(ConnectionInfo info, String action, ISendable data) {
                Log.e("TAG", "客户端发送数据回调");
                super.onSocketWriteResponse(info, action, data);
                Snackbar.make(view, "数据发送成功：" + new String(data.parse()), Snackbar.LENGTH_LONG).show();
                // Toast.makeText(SocketActivity.this, new String(data.parse()), Toast.LENGTH_SHORT).show();
            }
            //连接回调
            @Override
            public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
                super.onSocketConnectionFailed(info, action, e);
                String errorInfo = e.toString();
                Log.e("TAG", "onSocketConnectionFailed:" + errorInfo);
                String substring = errorInfo.substring(errorInfo.lastIndexOf(":"), errorInfo.length());
                Message msg = new Message();
                msg.what = 2;
                Bundle b = new Bundle();

                b.putString("data", substring);
                msg.setData(b);
                handler.sendMessage(msg);
                Looper.loop();
            }
            // 断开事件
            @Override
            public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
                super.onSocketDisconnection(info, action, e);
                // 断开连接
                Snackbar.make(view, "断开服务器连接,等待自动重连中....", Snackbar.LENGTH_LONG).show();
            }

        });
        manager.connect();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        manager.disconnect();
        handler = null;
    }
    // 发送实体
    public class TestSendData implements ISendable {
        private String str = "";

        public TestSendData() {


        }

        public TestSendData(String str) {
            this.str = str;
        }

        @Override
        public byte[] parse() {
            // 根据服务器的解析规则,构建byte数组
            byte[] body = str.getBytes(Charset.defaultCharset());
            return body;
        }
    }
}