package com.example.displaydemo;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

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

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


public class PD220Activity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "PD220Activity";

    private Button btn_display;
    private Button btn_display_upperlinescroll;
    private Button btn_display_at;
    private Button btn_restart;
    private Button btn_init;
    private Button btn_setbrightness;
    private Button btn_setcommand;
    private Button btn_setcharset;
    private Button btn_setcodepage;
    private Button btn_clearline;
    private Button btn_clearscreen;
    private Button btn_cursorleft;
    private Button btn_cursorright;
    private Button btn_cursordown;
    private Button btn_cursorup;
    private Button btn_cursorendleft;
    private Button btn_cursorendright;
    private Button btn_cursorhome;
    private Button btn_cursorend;
    private Button btn_movecursor;

    private Button btn_connect;
    private Button btn_back;

    private Spinner sp_port;
    private Spinner sp_baudrate;
    private Spinner sp_row;
    private Spinner sp_column;

    private Spinner sp_row_display;
    private Spinner sp_column_display;
    private Spinner sp_brightness;
    private Spinner sp_commands;
    private Spinner sp_charset;
    private Spinner sp_codepage;

    private EditText edt_text;

    private TextView tv_model;
    private TextView tv_firmwareVersion;

    private SerialPortFinder mSerialPortFinder;

    private DspAPI mDsp;

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

    private Runnable runnable;
    private ProgressDialog progressDialog;

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

    @Override
    public void initView() {
        btn_display = findViewById(R.id.btn_display);
        btn_display_upperlinescroll = findViewById(R.id.btn_display_upperlinescroll);
        btn_display_at = findViewById(R.id.btn_display_at);
        btn_restart = findViewById(R.id.btn_restart);
        btn_init = findViewById(R.id.btn_init);
        btn_clearline = findViewById(R.id.btn_clearline);
        btn_clearscreen = findViewById(R.id.btn_clearscreen);
        btn_cursorleft = findViewById(R.id.btn_cursorleft);
        btn_cursorright = findViewById(R.id.btn_cursorright);
        btn_cursordown = findViewById(R.id.btn_cursordown);
        btn_cursorup = findViewById(R.id.btn_cursorup);
        btn_cursorendleft = findViewById(R.id.btn_cursorendleft);
        btn_cursorendright = findViewById(R.id.btn_cursorendright);
        btn_cursorhome = findViewById(R.id.btn_cursorhome);
        btn_cursorend = findViewById(R.id.btn_cursorend);
        btn_movecursor = findViewById(R.id.btn_movecursor);
        btn_setbrightness = findViewById(R.id.btn_SetBrightness);
        btn_setcommand = findViewById(R.id.btn_SetCommand);
        btn_setcharset = findViewById(R.id.btn_setcharset);
        btn_setcodepage = findViewById(R.id.btn_setcodepage);

        btn_connect = findViewById(R.id.btn_connect);
        btn_back = findViewById(R.id.btn_back);

        sp_row = findViewById(R.id.spinner_row);
        sp_column = findViewById(R.id.spinner_column);
        sp_row_display = findViewById(R.id.spinner_row_display);
        sp_column_display = findViewById(R.id.spinner_column_display);
        sp_brightness = findViewById(R.id.spinner_Brightness);
        sp_commands = findViewById(R.id.spinner_Commands);
        sp_charset = findViewById(R.id.spinner_charset);
        sp_codepage = findViewById(R.id.spinner_codepage);

        edt_text = findViewById(R.id.edt_text);

        tv_model = findViewById(R.id.textModel);
        tv_firmwareVersion = findViewById(R.id.textFirmwareVersion);

        sp_port = findViewById(R.id.spinner_port);
        sp_baudrate = findViewById(R.id.spinner_baudrate);

        //serial port list
        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);

        //charset list
        List<String> allCharset_names = new ArrayList<String>();
        for (int i = 0; i < Constant.international_name.length; i++) {
            allCharset_names.add(Constant.international_name[i]);
        }
        ArrayAdapter<String> aspnCharset_names = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, allCharset_names);
        aspnCharset_names.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_charset.setAdapter(aspnCharset_names);

        //code page list
        List<String> allCodepage_names = new ArrayList<String>();
        for (int i = 0; i < Constant.codepage_name.length; i++) {
            allCodepage_names.add(Constant.codepage_name[i]);
        }
        ArrayAdapter<String> aspnCodepage_names = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, allCodepage_names);
        aspnCodepage_names.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_codepage.setAdapter(aspnCodepage_names);

    }

    @Override
    public void initData() {
        mDsp = new DspAPI(this);

        btn_display.setEnabled(false);
        btn_display_upperlinescroll.setEnabled(false);
        btn_display_at.setEnabled(false);
        btn_restart.setEnabled(false);
        btn_init.setEnabled(false);
        btn_clearline.setEnabled(false);
        btn_clearscreen.setEnabled(false);
        btn_cursorleft.setEnabled(false);
        btn_cursorright.setEnabled(false);
        btn_cursordown.setEnabled(false);
        btn_cursorup.setEnabled(false);
        btn_cursorendleft.setEnabled(false);
        btn_cursorendright.setEnabled(false);
        btn_cursorhome.setEnabled(false);
        btn_cursorend.setEnabled(false);
        btn_movecursor.setEnabled(false);

        btn_setbrightness.setEnabled(false);
        btn_setcommand.setEnabled(false);
        btn_setcharset.setEnabled(false);
        btn_setcodepage.setEnabled(false);
    }

    @Override
    protected void initListener() {
        btn_display.setOnClickListener(this);
        btn_display_upperlinescroll.setOnClickListener(this);
        btn_display_at.setOnClickListener(this);
        btn_restart.setOnClickListener(this);
        btn_init.setOnClickListener(this);
        btn_clearline.setOnClickListener(this);
        btn_clearscreen.setOnClickListener(this);
        btn_cursorleft.setOnClickListener(this);
        btn_cursorright.setOnClickListener(this);
        btn_cursordown.setOnClickListener(this);
        btn_cursorup.setOnClickListener(this);
        btn_cursorendleft.setOnClickListener(this);
        btn_cursorendright.setOnClickListener(this);
        btn_cursorhome.setOnClickListener(this);
        btn_cursorend.setOnClickListener(this);
        btn_movecursor.setOnClickListener(this);

        btn_setbrightness.setOnClickListener(this);
        btn_setcommand.setOnClickListener(this);
        btn_setcharset.setOnClickListener(this);
        btn_setcodepage.setOnClickListener(this);

        btn_connect.setOnClickListener(this);
        btn_back.setOnClickListener(this);
    }

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

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_display:
                String text1 = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !text1.isEmpty()) {
                    mDsp.DSP_Dispay(text1,
                            "ASCII");
                }
                break;
            case R.id.btn_display_upperlinescroll:
                String text2 = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !text2.isEmpty()) {
                    mDsp.DSP_Dispay_UpperLineScroll(text2,
                            "ASCII");
                }
                break;
            case R.id.btn_display_at:
                String text3 = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !text3.isEmpty()) {
                    mDsp.DSP_Dispay_At(text3,
                            "ASCII",
                            sp_row_display.getSelectedItemPosition() + 1,
                            sp_column_display.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_restart:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_Restart();
                }
                break;
            case R.id.btn_init:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_Init();
                }
                break;
            case R.id.btn_clearline:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ClearLine();
                }
                break;
            case R.id.btn_clearscreen:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ClearScreen();
                }
                break;
            case R.id.btn_cursorleft:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorLeft();
                }
                break;
            case R.id.btn_cursorright:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorRight();
                }
                break;
            case R.id.btn_cursordown:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorDown();
                }
                break;
            case R.id.btn_cursorup:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorUp();
                }
                break;
            case R.id.btn_cursorendleft:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorEndLeft();
                }
                break;
            case R.id.btn_cursorendright:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorEndRight();
                }
                break;
            case R.id.btn_cursorend:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorEnd();
                }
                break;
            case R.id.btn_cursorhome:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorHome();
                }
                break;
            case R.id.btn_movecursor:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursor(sp_row.getSelectedItemPosition() + 1,
                            sp_column.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_SetBrightness:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetBrightness(sp_brightness.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_SetCommand:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetCommandSet(sp_commands.getSelectedItemPosition());
                }
                break;
            case R.id.btn_setcharset:
                if (mDsp != null && mDsp.isConnect()) {
                    int i = sp_charset.getSelectedItemPosition();
                    mDsp.DSP_SetCharset(Constant.international_no[i]);
                }
                break;
            case R.id.btn_setcodepage:
                if (mDsp != null && mDsp.isConnect()) {
                    int i = sp_codepage.getSelectedItemPosition();
                    mDsp.DSP_SetCodepage(Constant.codepage_no[i]);
                }
                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 (mDsp != null && mDsp.isConnect()) {
                    mDsp.disconnect();
                }
                mDsp = null;
                this.finish();
                break;
        }
    }

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

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

    }

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

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

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

                    int version = mDsp.DSP_GetFirmwareVersion_VFD();
                    if (version > 0)
                        tv_firmwareVersion.setText("Firmware Version: " + version);
                    else
                        tv_firmwareVersion.setText("Firmware Version: unknown");

                    btn_display.setEnabled(true);
                    btn_display_upperlinescroll.setEnabled(true);
                    btn_display_at.setEnabled(true);
                    btn_restart.setEnabled(true);
                    btn_init.setEnabled(true);
                    btn_clearline.setEnabled(true);
                    btn_clearscreen.setEnabled(true);
                    btn_cursorleft.setEnabled(true);
                    btn_cursorright.setEnabled(true);
                    btn_cursordown.setEnabled(true);
                    btn_cursorup.setEnabled(true);
                    btn_cursorendleft.setEnabled(true);
                    btn_cursorendright.setEnabled(true);
                    btn_cursorhome.setEnabled(true);
                    btn_cursorend.setEnabled(true);
                    btn_movecursor.setEnabled(true);

                    btn_setbrightness.setEnabled(true);
                    btn_setcommand.setEnabled(true);
                    btn_setcharset.setEnabled(true);
                    btn_setcodepage.setEnabled(true);
                    break;
                case 1:
                    ToastUtils.showToast(serialPort + " Connect failed");

                    btn_display.setEnabled(false);
                    btn_display_at.setEnabled(false);
                    btn_restart.setEnabled(false);
                    btn_init.setEnabled(false);
                    btn_clearline.setEnabled(false);
                    btn_clearscreen.setEnabled(false);
                    btn_cursorleft.setEnabled(false);
                    btn_cursorright.setEnabled(false);
                    btn_cursordown.setEnabled(false);
                    btn_cursorup.setEnabled(false);
                    btn_cursorendleft.setEnabled(false);
                    btn_cursorendright.setEnabled(false);
                    btn_cursorhome.setEnabled(false);
                    btn_cursorend.setEnabled(false);
                    btn_movecursor.setEnabled(false);

                    btn_setbrightness.setEnabled(false);
                    btn_setcommand.setEnabled(false);
                    btn_setcharset.setEnabled(false);
                    btn_setcodepage.setEnabled(false);
                    break;
            }
        }
    };
}
