package com.example.displaydemo;


import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ToggleButton;

import com.example.displaydemo.base.BaseActivity;
import com.example.displaydemo.utils.ToastUtils;
import com.pavolibrary.commands.LedAPI;
import com.serialport.api.SerialPortFinder;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class PD108Activity extends BaseActivity implements View.OnClickListener,
        ToggleButton.OnCheckedChangeListener, Spinner.OnItemSelectedListener {
    private static final String TAG = "PD108Activity";

    private Button btn_display;
    private Button btn_clearline;
    private Button btn_clearscreen;
    private Button btn_init;
    private Button btn_setting;
    private Button btn_back;

    private Spinner sp_port;
    private Spinner sp_baudrate;
    private Spinner sp_baudrate_set;
    private Spinner sp_movecursor;
    private Spinner sp_setstatuslight;

    private EditText edt_text;

    private ToggleButton tbtn_setCursorState;
    private ToggleButton tbtn_keepTesting;

    private SerialPortFinder mSerialPortFinder;

    private LedAPI mLed8;

    private String serialPort = "USB";  //定义串口号
    private int serialBaudrate = 9600;  //定义波特率
    private int serialFlag = 0;

    private Runnable runnable;


    private Timer timerKeppTesting;       //测试开钱箱
    private boolean isTesting = false;
    private int testDisplayCount = 1;
    private int testStatusCount = 1;

    @Override
    public int getContentViewId() {
        return R.layout.activity_pd108;
    }

    @Override
    public void initView() {
        btn_display = findViewById(R.id.btn_display);
        btn_clearline = findViewById(R.id.btn_clearline);
        btn_clearscreen = findViewById(R.id.btn_clearscreen);
        btn_init = findViewById(R.id.btn_init);
        btn_setting = findViewById(R.id.btn_connect);
        btn_back = findViewById(R.id.btn_back);
        sp_port = findViewById(R.id.spinner_port);
        sp_baudrate = findViewById(R.id.spinner_baudrate);
        sp_baudrate_set = findViewById(R.id.spinner_baudrate_set);
        sp_movecursor = findViewById(R.id.spinner_movecursor);
        sp_setstatuslight = findViewById(R.id.spinner_setstatus);

        edt_text = findViewById(R.id.edt_text);

        tbtn_setCursorState = findViewById(R.id.tbtn_setCursorState);
        tbtn_keepTesting = findViewById(R.id.tbtn_keeptesting);

        mSerialPortFinder = new SerialPortFinder();
        String[] entryValues = mSerialPortFinder.getAllDevicesPath();
        List<String> allDevices = new ArrayList<String>();
        allDevices.add("USB");
        for (int i = 0; i < entryValues.length; i++) {
            allDevices.add(entryValues[i]);
        }

        ArrayAdapter<String> aspnDevices = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, allDevices);
        aspnDevices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_port.setAdapter(aspnDevices);

    }

    @Override
    public void initData() {
        mLed8 = new LedAPI(this);

        btn_display.setEnabled(false);
        btn_clearline.setEnabled(false);
        btn_clearscreen.setEnabled(false);
        btn_init.setEnabled(false);
        sp_baudrate_set.setEnabled(false);
        sp_movecursor.setEnabled(false);
        sp_setstatuslight.setEnabled(false);

        tbtn_setCursorState.setEnabled(false);
        tbtn_keepTesting.setEnabled(false);
    }

    @Override
    protected void initListener() {
        btn_display.setOnClickListener(this);
        btn_clearline.setOnClickListener(this);
        btn_clearscreen.setOnClickListener(this);
        btn_init.setOnClickListener(this);
        btn_setting.setOnClickListener(this);
        btn_back.setOnClickListener(this);

        sp_baudrate_set.setOnItemSelectedListener(this);
        sp_movecursor.setOnItemSelectedListener(this);
        sp_setstatuslight.setOnItemSelectedListener(this);

        tbtn_setCursorState.setOnCheckedChangeListener(this);
        tbtn_keepTesting.setOnCheckedChangeListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLed8 != null) {
            mLed8.disconnect();
            mLed8 = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_display:
                String text = edt_text.getText().toString().trim();
                if (mLed8 != null && mLed8.isConnect() && !text.isEmpty()) {
                    mLed8.LED_Display(text, "ASCII");
                }
                break;
            case R.id.btn_clearline:
                if (mLed8 != null && mLed8.isConnect()) {
                    mLed8.LED_ClearLine();
                }
                break;
            case R.id.btn_clearscreen:
                if (mLed8 != null && mLed8.isConnect()) {
                    mLed8.LED_ClearScreen();
                }
                break;
            case R.id.btn_init:
                if (mLed8 != null && mLed8.isConnect()) {
                    mLed8.LED_Init();
                }
                break;
            case R.id.btn_connect:
                this.serialPort = sp_port.getSelectedItem().toString();
                this.serialBaudrate = Integer.parseInt(sp_baudrate.getSelectedItem().toString());
                connect();
                break;
            case R.id.btn_back:
                if (mLed8 != null && mLed8.isConnect()) {
                    mLed8.disconnect();
                }
                mLed8 = null;
                this.finish();
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.tbtn_setCursorState:
                if (isChecked) {
                    if (mLed8 != null && mLed8.isConnect()) {
                        mLed8.LED_SetCursorFlag(1);
                    }
                } else {
                    if (mLed8 != null && mLed8.isConnect()) {
                        mLed8.LED_SetCursorFlag(0);
                    }
                }
                break;
            case R.id.tbtn_keeptesting:
                if (isChecked) {
                    if (mLed8 != null && mLed8.isConnect()) {
                        cancelKeepTesting();
                        keepTesting();
                    }
                } else {
                    cancelKeepTesting();
                }
                break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spinner_baudrate_set:
                if (mLed8 != null && mLed8.isConnect()) {
                    mLed8.LED_SetBaudRate(sp_baudrate_set.getSelectedItemPosition());
                }
                break;
            case R.id.spinner_movecursor:
                if (mLed8 != null && mLed8.isConnect()) {
                    mLed8.LED_MoveCursor(sp_movecursor.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.spinner_setstatus:
                if (mLed8 != null && mLed8.isConnect()) {
                    mLed8.LED_SetStatusLight(sp_setstatuslight.getSelectedItemPosition());
                }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    /**
     * 连接
     */
    private void connect() {
        if (mLed8 != null) {
            mLed8.clearbuffer();
            mLed8.disconnect();
        }
        runnable = new Runnable() {
            @Override
            public void run() {

                if (mLed8.SUCCESS == mLed8.connect(serialPort, serialBaudrate, serialFlag)) {
                    showHandler.sendEmptyMessage(0);
                } else {
                    showHandler.sendEmptyMessage(1);
                }
            }
        };
        new Thread(runnable).start();
    }

    private static class NoLeakHandler extends Handler {
        WeakReference<PD108Activity> wf;

        private NoLeakHandler(PD108Activity activity) {
            wf = new WeakReference(activity);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler showHandler = new NoLeakHandler(PD108Activity.this) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ToastUtils.showToast(serialPort + " Connect successful");

                    btn_display.setEnabled(true);
                    btn_clearline.setEnabled(true);
                    btn_clearscreen.setEnabled(true);
                    btn_init.setEnabled(true);
                    sp_baudrate_set.setEnabled(true);
                    sp_movecursor.setEnabled(true);
                    sp_setstatuslight.setEnabled(true);

                    tbtn_setCursorState.setEnabled(true);
                    tbtn_keepTesting.setEnabled(true);
                    break;
                case 1:
                    ToastUtils.showToast(serialPort + " Connect failed");

                    btn_display.setEnabled(false);
                    btn_clearline.setEnabled(false);
                    btn_clearscreen.setEnabled(false);
                    btn_init.setEnabled(false);
                    sp_baudrate_set.setEnabled(false);
                    sp_movecursor.setEnabled(false);
                    sp_setstatuslight.setEnabled(false);

                    tbtn_setCursorState.setEnabled(false);
                    tbtn_keepTesting.setEnabled(false);
                    break;
            }
        }
    };

    /**
     * 循环测试
     */
    public void keepTesting() {
        try {
            if (timerKeppTesting == null) {

                timerKeppTesting = new Timer();
                timerKeppTesting.schedule(new TimerTask() {
                    boolean Testflag = false;

                    public void run() {
                        if (Testflag) return;
                        Testflag = true;
                        isTesting = true;

                        if (mLed8 != null && mLed8.isConnect()) {
                            if (testStatusCount == 0)
                                testStatusCount = 4;
                            mLed8.LED_SetStatusLight(testStatusCount);
                            switch (testStatusCount){
                                case 4:
                                    mLed8.LED_Display("8.8.","ASCII");
                                    break;
                                case 3:
                                    mLed8.LED_Display("8.8.8.8.","ASCII");
                                    break;
                                case 2:
                                    mLed8.LED_Display("8.8.8.8.8.8.","ASCII");
                                    break;
                                case 1:
                                    mLed8.LED_Display("8.8.8.8.8.8.8.8.","ASCII");
                                    break;
                            }
                            testStatusCount--;
                        }

                        Testflag = false;
                    }
                }, 0, 1000);
            }
        } catch (Exception e) {
            isTesting = false;
        }
    }

    /**
     * 退出循环测试
     */
    private void cancelKeepTesting() {
        if (timerKeppTesting != null) {
            timerKeppTesting.cancel();
            timerKeppTesting = null;
            testStatusCount = 4;
            isTesting = false;
        }
    }

}
