package com.fuhengtech.testled;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialApp;


public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    SerialApp serialApp = new SerialApp();
    TextView textViewStatus;
    Button btnOpen;
    Button btnClose;
    Button btnLightOn;
    Spinner spinnerLedNum;
    Button btnLightOff;
    Button btnLightFlash;
    EditText editTextFlashNum;

    OutputStream mOutputStream = null;
    InputStream mInputStream = null;

    boolean bOpenSuccess=false;
    String devicePath = "";
    int nLedNum = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initCtrls();
        OnBtnClicked();
    }

    private void OnBtnClicked()
    {
        btnOpen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                bOpenSuccess = true;
                try {
                    //mInputStream = serialApp.getSerialPort().getInputStream();
                    mOutputStream = serialApp.getSerialPort().getOutputStream();
                } catch (IOException e) {
                    bOpenSuccess = false;
                    e.printStackTrace();
                }
                catch (SecurityException e)
                {
                    bOpenSuccess = false;
                    e.printStackTrace();
                }
                if (bOpenSuccess)
                {
                    textViewStatus.setText("succeed to open " + devicePath );
                }
                else
                {
                    textViewStatus.setText("Failed to open " + devicePath );
                }
                updateCtrls();
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                serialApp.closeSerialPort();
                bOpenSuccess = false;
                updateCtrls();
                textViewStatus.setText("Close " + devicePath );
            }
        });

        btnLightOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strLenNum = spinnerLedNum.getSelectedItem().toString();
                byte[] buf = new byte[3];
                buf[0] = (byte)(0xF1 + nLedNum);
                buf[1] = 0x01;
                buf[2] = 0x00;
                try {
                    mOutputStream.write(buf);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


        btnLightOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] buf = new byte[3];
                buf[0] = (byte)(0xF1 + nLedNum);
                buf[1] = 0x00;
                buf[2] = 0x00;
                try {
                    mOutputStream.write(buf);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        btnLightFlash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String strLenNum = spinnerLedNum.getSelectedItem().toString();
                int nFlashNum = Integer.parseInt(editTextFlashNum.getText().toString());
                byte[] buf = new byte[3];
                buf[0] = (byte)(0xF1 + nLedNum);
                buf[1] = 0x02;
                buf[2] =(byte)(0x00 + nFlashNum) ;
                try {
                    mOutputStream.write(buf);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initCtrls()
    {
        InitButtons();
        InitTextView();
        InitSpinner();      //要用到TextView
        InitEditText();
    }

    private void InitEditText()
    {
        editTextFlashNum = (EditText) findViewById(R.id.editTextFlashNum);
        editTextFlashNum.setEnabled(false);
        editTextFlashNum.clearFocus();
    }

    private void InitButtons()
    {
        btnOpen = (Button)findViewById(R.id.btnOpen);
        btnOpen.setEnabled(true);
        btnClose = (Button)findViewById(R.id.btnClose);
        btnClose.setEnabled(false);
        btnLightOn = (Button)findViewById(R.id.btnLightOn);
        btnLightOn.setEnabled(false);
        btnLightOff = (Button)findViewById(R.id.btnLightOff);
        btnLightOff.setEnabled(false);
        btnLightFlash = (Button)findViewById(R.id.btnLightFlash);
        btnLightFlash.setEnabled(false);
    }

    private void updateCtrls()
    {
        btnOpen.setEnabled(!bOpenSuccess);
        btnClose.setEnabled(bOpenSuccess);
        btnLightOn.setEnabled(bOpenSuccess);
        btnLightOff.setEnabled(bOpenSuccess);
        btnLightFlash.setEnabled(bOpenSuccess);
        editTextFlashNum.setEnabled(bOpenSuccess);
    }

    private void InitTextView()
    {
        textViewStatus = (TextView)findViewById(R.id.textViewStatus);
    }

    private void InitSpinner()
    {
        InitPortSpinner();
        InitBaudrateSpinner();
        InitLedNumSpinner();
    }

    private void InitLedNumSpinner()
    {
        spinnerLedNum = (Spinner)findViewById(R.id.spinnerLedNum);
        spinnerLedNum.setOnItemSelectedListener(this);
    }
    
    private void InitBaudrateSpinner() {
        final Spinner spinnerBaudrate = (Spinner) findViewById(R.id.spinnerBaudrate);
        String baudrate = spinnerBaudrate.getSelectedItem().toString();
        serialApp.set_baudrate(Integer.parseInt(baudrate));
        spinnerBaudrate.setOnItemSelectedListener(this);
    }

    private void InitPortSpinner() {
        // Devices
        exeShell("chmod 777 /proc/tty/driver");  //get root
        //String[] deviceNames  = serialApp.mSerialPortFinder.getAllDevices();     //ttyS0(serial)
        String[] devicePaths = serialApp.mSerialPortFinder.getAllDevicesPath();      // /dev/ttyS0

        //2.get spinner id
        final Spinner spinnerPort = (Spinner) findViewById(R.id.spinnerPort);

        //3.display device on the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, devicePaths);  //创建一个数组适配器
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);                                         //设置下拉列表框的下拉选项样式
        spinnerPort.setAdapter(adapter);

        if(devicePaths.length > 0)
        {
            spinnerPort.setSelection(devicePaths.length - 1);
            devicePath = spinnerPort.getSelectedItem().toString();
            textViewStatus.setText(devicePath);
            serialApp.set_device(devicePath);
        }
        spinnerPort.setOnItemSelectedListener(this);
    }

    public void onItemSelected (AdapterView<?> parent, View view, int position, long id)
    {
        switch (parent.getId())
        {
            case R.id.spinnerPort:
            {
                devicePath = parent.getSelectedItem().toString();
                textViewStatus.setText(devicePath);
                serialApp.set_device(devicePath);
                break;
            }
            case R.id.spinnerBaudrate:
            {
                String baudrate = parent.getSelectedItem().toString();
                serialApp.set_baudrate(Integer.parseInt(baudrate));
                break;
            }
            case R.id.spinnerLedNum:
            {
                nLedNum = position;
                break;
            }
        }
    }
    public void onNothingSelected(AdapterView<?> parent)
    {

    }
    public void exeShell(String cmd){
        DataOutputStream os = null;
        try{
            Process su = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(su.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            su.waitFor();
        }
        catch(Throwable t)
        {
            t.printStackTrace();
        }
    }


}
