package com.hardkernel.odroid.oduino;

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

import com.hardkernel.odroid.serialport.SerialPort;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
    
    protected SerialPort mSerialPort = null;
    protected OutputStream mOutputStream;
    private InputStream mInputStream;
    private ReadThread mReadThread;
    
    private TextView mCelsius_Tv;
    private ProgressBar mCelsius_Pb;
    private TextView mFahrenheit_Tv;
    private ProgressBar mFahrenheit_Pb;
    private TextView mHumidity_Tv;
    private ProgressBar mHumidity_Pb;
    
    private class ReadThread extends Thread {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();
            while(!isInterrupted()) {
                int size;
                try {
                    byte[] buffer = new byte[32];
                    if (mInputStream == null)
                        return;
                    size = mInputStream.read(buffer);
                    if (size > 0) {
                        onDataReceived(buffer, size);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }
        
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mCelsius_Tv = (TextView)findViewById(R.id.tv_celsius);
        mCelsius_Pb = (ProgressBar)findViewById(R.id.pb_celsius);
        
        mFahrenheit_Tv = (TextView)findViewById(R.id.tv_fahrenheit);
        mFahrenheit_Pb = (ProgressBar)findViewById(R.id.pb_fahrenheit);
        
        mHumidity_Tv = (TextView)findViewById(R.id.tv_humidity);
        mHumidity_Pb = (ProgressBar)findViewById(R.id.pb_humidity);

        try {
            mSerialPort = new SerialPort(new File("/dev/ttyACM0"), 115200, 0);
            mOutputStream = mSerialPort.getOutputStream();
            mInputStream = mSerialPort.getInputStream();
            
            mReadThread = new ReadThread();
            mReadThread.start();
        } catch (SecurityException e) {
            DisplayError(R.string.error_security);
        } catch (IOException e) {
            DisplayError(R.string.error_unknown);
        } 
    }
    
    protected void onDataReceived(final byte[] buffer, final int size) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (size == 12 && buffer[0] == 'O' && buffer[1] == 'K') {
                    int humidity = 0;
                    int i = 3;
                    for (; i < size; i++) {
                        
                        if (buffer[i] >= '0' && buffer[i] <= '9') {
                            humidity = (buffer[i] - '0') * 10;
                            humidity += buffer[i + 1] - '0';
                            i += 2;
                            break;
                        }
                    }
                    
                    mHumidity_Pb.setProgress(humidity);
                    mHumidity_Tv.setText(Integer.toString(humidity));
                    
                    int celsius = 0;
                    for (; i < size; i++) {
                        if (buffer[i] >= '0' && buffer[i] <= '9') {
                            celsius = (buffer[i] - '0') * 10;
                            celsius += buffer[i] - '0';
                            break;
                        }
                    }
                    
                    mCelsius_Pb.setProgress(celsius + 25);
                    mCelsius_Tv.setText(Integer.toString(celsius));
                    
                    int fahrenheit = (int) (celsius * 1.8 + 32);
                    
                    mFahrenheit_Pb.setProgress(fahrenheit + 13);
                    mFahrenheit_Tv.setText(Integer.toString(fahrenheit));
                //Log.e("aaa", "humidity = " + humidity + " celsius = " + celsius);
                }
            }
        });
    }
    
    private void DisplayError(int resourceId) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle("Error");
        b.setMessage(resourceId);
        b.setPositiveButton("OK", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                MainActivity.this.finish();
            }
        });
        b.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    protected void onDestroy() {
        if (mReadThread != null)
            mReadThread.interrupt();
        mSerialPort.close();
        mSerialPort = null;
        super.onDestroy();
    }

}
