package com.wsm.usbhiddemo;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


import com.wsm.hidlib.HIDManager;
import com.wsm.hidlib.HidLibConfig;
import com.wsm.hidlib.callback.HIDDataListener;
import com.wsm.hidlib.callback.HIDOpenListener;
import com.wsm.hidlib.callback.HIDSequenceNumberListener;
import com.wsm.hidlib.constant.ConnectCostant;
import com.wsm.hidlib.constant.FormatConstant;
import com.wsm.hidlib.util.StringFormat;


public class MainActivity extends AppCompatActivity {

    private static String TAG = "MainActivity_tag";
    private int READ_OK = 1;
    private TextView tvInfo;
    private EditText edtContent;
    private RadioGroup rdg;
    private Context mContext;
    private HIDOpenListener mHIDOpenListener;
    private HIDDataListener mHidDataListener;
    private TextView txt_connect;
    private StringBuffer stringBuffer;
    private int contentLength;
    private TextView contentlenth;
    private HIDSequenceNumberListener mHidSequenceNumberListener;
    private String foramt = FormatConstant.FORMAT_UTF8;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == READ_OK) {
                String data = (String) msg.obj;
                int length = stringBuffer.length();
                if (length > 1024 * 10) {
                    stringBuffer.delete(0, length);
                    tvInfo.scrollTo(0, 0);
                }
                tvInfo.setText(stringBuffer.append(data));
                int l = contentLength + data.length();
                contentLength = l;
                contentlenth.setText("length:" + l);

                int offset = tvInfo.getLineCount() * tvInfo.getLineHeight();
                if (offset > tvInfo.getHeight()) {
                    tvInfo.scrollTo(0, offset - tvInfo.getHeight());
                }
            }
        }
    };
    private TextView txt_deviceid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = MainActivity.this;
        stringBuffer = new StringBuffer();
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        initHID();
        Log.d(TAG, "activity onCreate: ");

    }

    @Override
    protected void onResume() {
        Log.d(TAG, "activity onResume: ");
        super.onResume();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.d(TAG, "onConfigurationChanged: "+newConfig.toString());
        super.onConfigurationChanged(newConfig);

    }

    private void initView() {
        contentlenth = findViewById(R.id.contentlenth);
        tvInfo = findViewById(R.id.received);
        tvInfo.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvInfo.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipboardManager copy = (ClipboardManager) mContext
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                copy.setText(tvInfo.getText());
                Toast.makeText(mContext, "已复制到粘贴板", Toast.LENGTH_SHORT).show();
                return false;
            }
        });


        edtContent = findViewById(R.id.edt);
        rdg = findViewById(R.id.rdg);


        rdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rgbGBK:
                        HIDManager.getInstance().setFormat(FormatConstant.FORMAT_GBK);
                        foramt = FormatConstant.FORMAT_GBK;
                        break;
                    case R.id.rgbUTF8:
                        HIDManager.getInstance().setFormat(FormatConstant.FORMAT_UTF8);
                        foramt = FormatConstant.FORMAT_UTF8;
                        break;
                    case R.id.rgbHex:
                        HIDManager.getInstance().setFormat(FormatConstant.FORMAT_HEX);
                        foramt = FormatConstant.FORMAT_HEX;
                        break;
                    default:
                }
            }
        });
        rdg.check(rdg.getChildAt(1).getId());

        txt_connect = findViewById(R.id.txt_connect_status);
        txt_deviceid = findViewById(R.id.txt_deviceid);
        txt_deviceid.setText("VID:" + Integer.toHexString(HidLibConfig.deviceVID) +
                " PID:" + Integer.toHexString(HidLibConfig.devicePID)
        );
        Button btn_getsn = findViewById(R.id.btn_getsn);
        btn_getsn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HIDManager.getInstance().getSequenceNumber(mHidSequenceNumberListener);
            }
        });
        Button btn_disconnect = findViewById(R.id.btn_disconnect);
        btn_disconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HIDManager.getInstance().closeHID();
            }
        });
        Button btn_set_device_id = findViewById(R.id.btn_set_device_id);
        btn_set_device_id.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDeviceIDDialog();
            }
        });
        Button btn_connect = findViewById(R.id.btn_connect);
        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HIDManager.getInstance().openHID(mContext, mHIDOpenListener, mHidDataListener);
            }
        });
        Button btn_set_time = findViewById(R.id.btn_set_time);
        btn_set_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setTimeDialog();
            }
        });
        Button btn_send = findViewById(R.id.btn_send);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendData();
            }
        });
        Button btn_clear = findViewById(R.id.btn_clear);
        btn_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (stringBuffer != null) {
                    stringBuffer.delete(0, stringBuffer.length());
                } else {
                    stringBuffer = new StringBuffer();
                }
                contentLength = 0;
                tvInfo.setText(stringBuffer);
                contentlenth.setText("length:" + contentLength);
                tvInfo.scrollTo(0, 0);
            }
        });

    }

    private void initListener() {
        //回调数据有关页面展示的请在主线程进行。
        mHIDOpenListener = new HIDOpenListener() {
            @Override
            public void openSuccess(final int openSuccessStatus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (openSuccessStatus == ConnectCostant.USB_CONNECT) {
                            txt_connect.setText("连接USB");
                            Toast.makeText(MainActivity.this, "连接USB", Toast.LENGTH_LONG).show();
                            txt_deviceid.setText("VID:" + Integer.toHexString(HidLibConfig.deviceVID) +
                                    " PID:" + Integer.toHexString(HidLibConfig.devicePID)
                            );

                        } else if (openSuccessStatus == ConnectCostant.COMMUNICATION_OPEN) {
                            txt_connect.setText("通讯建立");
                            Toast.makeText(MainActivity.this, "通讯建立", Toast.LENGTH_LONG).show();
                        }
                    }
                });

            }

            @Override
            public void openError(int openErrorStatus) {
                if (openErrorStatus == ConnectCostant.USB_DISCONNECT) {
                    //USB断开
                    txt_connect.setText("断开USB");
                    Toast.makeText(MainActivity.this, "断开USB", Toast.LENGTH_LONG).show();
                }
                if (openErrorStatus == ConnectCostant.COMMUNICATION_CLOSE) {
                    //服务销毁
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            txt_connect.setText("通讯断开");
                            Toast.makeText(MainActivity.this, "通讯断开", Toast.LENGTH_LONG).show();

                        }
                    });

                }
            }

        };

        mHidDataListener = new HIDDataListener() {
            @Override
            public void onDataReceived(byte status, String dataMessage) {
                if (!TextUtils.isEmpty(dataMessage)) {
                    String result = dataMessage;
                    Log.d(TAG, "onDataReceived: length:" + dataMessage.length() + "   content:" + result);
                    Message message = Message.obtain();
                    message.what = READ_OK;
                    message.obj = result;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onOriginalDataReceived(byte status, byte[] bytes, int length) {
//                String formatHexString = HexUtil.formatHexString(bytes);
                Log.d(TAG, "onOriginalDataReceived: " + length);

            }
        };
        mHidSequenceNumberListener = new HIDSequenceNumberListener() {
            @Override
            public void onSequenceNumberReceived(byte[] bytes, int length) {
                if (length > 0) {
                    String formatChar = StringFormat.bytes2String(bytes, foramt);
                    Log.d(TAG, "onSequenceNumberReceived: " + formatChar);
                    Message message = Message.obtain();
                    message.what = READ_OK;
                    message.obj = formatChar;
                    handler.sendMessage(message);
                }
            }
        };

    }

    private void initHID() {
        HIDManager.getInstance().enableLog(true);
        HIDManager.getInstance().openHID(mContext, mHIDOpenListener, mHidDataListener);

    }

    public void sendData() {
        String str_hex = edtContent.getText().toString();
        Log.d(TAG, str_hex.length() + "  sendData: " + str_hex);
        if ((str_hex.length() == 0)) {
            Toast.makeText(MainActivity.this, "请输入符合16进制的有效字符", Toast.LENGTH_LONG).show();
            return;
        } else if (str_hex.length() % 2 != 0) {
            Toast.makeText(MainActivity.this, "请输入2的倍数的组合", Toast.LENGTH_LONG).show();
            return;
        }

        for (int i = 0; i <= str_hex.length() - 1; i++) {
            if (!(((str_hex.charAt(i) >= '0') && (str_hex.charAt(i) <= '9')) ||
                    ((str_hex.charAt(i) >= 'a') && (str_hex.charAt(i) <= 'f')) ||
                    ((str_hex.charAt(i) >= 'A') && (str_hex.charAt(i) <= 'F')))) {
                Toast.makeText(MainActivity.this, "请输入符合16进制的有效字符", Toast.LENGTH_LONG).show();
                return;
            }
        }

        //发送数据
        HIDManager.getInstance().sendData(str_hex);
    }

    private void setDeviceIDDialog() {
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        final EditText et = new EditText(this);
        final EditText et2 = new EditText(this);
//        et.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        et.setHint("请输入VID");
        et2.setHint("请输入PID");
//        et2.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        linearLayout.addView(et);
        linearLayout.addView(et2);
        new AlertDialog.Builder(this).setTitle("设置设备VID/PID")
                .setMessage("请输入要连接的设备VID/PID")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setView(linearLayout)
//                .setView(et2)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String input1 = et.getText().toString();
                        String input2 = et2.getText().toString();
                        if (TextUtils.isEmpty(input1)) {
                            Toast.makeText(getApplicationContext(), "输入VID数字不能为空！" + input1, Toast.LENGTH_LONG).show();
                        }
                        if (TextUtils.isEmpty(input2)) {
                            Toast.makeText(getApplicationContext(), "输入PID数字不能为空！" + input2, Toast.LENGTH_LONG).show();
                        } else {
                            try {
                                boolean setDeviceIDTimeOut = HIDManager.getInstance().addDeviceID(Integer.parseInt(input1, 16), Integer.parseInt(input2, 16));
                                if (setDeviceIDTimeOut) {
                                    Toast.makeText(getApplicationContext(), "设置设备VID/PID" + "成功！下次连接时生效。", Toast.LENGTH_LONG).show();

                                } else {
                                    Toast.makeText(getApplicationContext(), "设置设备VID/PID" + "失败,情检查设置范围！", Toast.LENGTH_LONG).show();

                                }
                            } catch (Exception exception) {
                                Toast.makeText(getApplicationContext(), "设置设备VID/PID" + "失败,情检查设置数字！", Toast.LENGTH_LONG).show();
                            }


                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void setTimeDialog() {
        final EditText et = new EditText(this);
        et.setInputType(EditorInfo.TYPE_CLASS_PHONE);

        new AlertDialog.Builder(this).setTitle("设置超时时间")
                .setMessage("设置范围【50-5000】，默认500ms")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (TextUtils.isEmpty(input)) {
                            Toast.makeText(getApplicationContext(), "输入数字不能为空！" + input, Toast.LENGTH_LONG).show();
                        } else {
                            boolean setPackageTimeOut = HIDManager.getInstance().setPackageTimeOut(Integer.parseInt(input));
                            if (setPackageTimeOut) {
                                Toast.makeText(getApplicationContext(), "设置超时时间" + input + "ms 成功！", Toast.LENGTH_LONG).show();

                            } else {
                                Toast.makeText(getApplicationContext(), "设置超时时间" + input + "ms 失败,情检查设置范围！", Toast.LENGTH_LONG).show();

                            }

                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }


    @Override
    protected void onDestroy() {
        ////关闭连接，建议在onDestroy调用,解绑服务并释放资源
        Log.d(TAG, "activity onDestroy: ");
        HIDManager.getInstance().closeHID();
        super.onDestroy();
    }


}
