/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.geotools.Accelerometer;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author BURKAY
 */
public class CommListener {
    static int X;
    static int Y;
    static int Z;
    private static String stream="";
    private static String message="";
    
    public CommListener(){
        super();
        
    }



    public void main(){
        
        try {
            
            String comport = AccelerometerInterface.getjTextField4().getText();
            connect(comport);
        } catch (Exception ex) {
            Logger.getLogger(CommListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void connect(String port) throws Exception {
        ipAddress = AccelerometerInterface.getjTextField1().getText();
        portNumber = Integer.parseInt(AccelerometerInterface.getjTextField2().getText());
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port);
        if(portIdentifier.isCurrentlyOwned()){
            System.out.println("Error: port is currently in use");
        }
        else {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
            if(commPort instanceof SerialPort){
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialReader(in))).start(); 
            }
            else{
                System.out.println("Error: Only serial ports are handled");
            }
        }
    }

    public static class SerialReader extends Thread{
        InputStream in;

        public SerialReader(InputStream in){
            this.in = in;
        }

       public void sendData(String data) throws Exception{

            DatagramSocket socket = new DatagramSocket();

            byte[] buf = new byte[256];
            buf = data.getBytes();
            InetAddress addr = InetAddress.getByName(ipAddress);
            DatagramPacket packet = new DatagramPacket(buf, buf.length, addr, portNumber);

            socket.send(packet);
            AccelerometerInterface.getjTextPane2().setText(
                    line+"\n"+AccelerometerInterface.getjTextPane2().getText());
        }
       
        private void prepareStreamData(){
            String xval = line.substring(2, 6);
            String yval = line.substring(9, 13);
            String zval = line.substring(16, 20);
            
            Integer x = Integer.parseInt(xval, 16);
            Integer y = Integer.parseInt(yval, 16);
            Integer z = Integer.parseInt(zval, 16);
            
            if(x>32767) x = x-65536;
            if(y>32767) y = y-65536;
            if(z>32767) z = z-65536;
            //x = (x+16)/256;
            //y = (y+16)/256;
            //z = (z+16)/256;
            
            Double zd = z*1.0;

            double xang = java.lang.Math.atan(x/zd);
            double yang = java.lang.Math.atan(y/zd);

            if(xang>-360.0 && xang < 360.0) {
            } else {
                xang = 0;
            }
            if(yang>-360.0 && yang < 360.0) {
            } else {
                yang = 0;
            }

            xang = (xang*180)/java.lang.Math.PI;
            yang = (yang*180)/java.lang.Math.PI;

            line = decForm.format(xang)+" | "+decForm.format(yang);
            System.out.println(line);
        }
    

        @Override
        public void run(){
            byte[] buffer = new byte[1024];
            int len = -1;
            int turn = 99;
            try{
                while((len = this.in.read(buffer)) > -1){
                    if(AccelerometerInterface.stream == false) break;
                    String stream2 = new String(buffer,0,len);
                    message += stream2;
                    if(message.length()>=21){
                        turn++;
                        stream = message.substring(0, 20);
                        line = stream;
                        message = message.substring(21, message.length());
                        if(turn==100){
                            turn=0;
                            System.out.println(line);
                            AccelerometerInterface.getjTextPane1().setText(
                                line+"\n"+AccelerometerInterface.getjTextPane1().getText());
                            try {
                                prepareStreamData();
                                sendData(line);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            } catch(IOException ex){
                ex.printStackTrace();
            }
        }
    }



    public void st(){
        try{
            (new CommListener()).connect(AccelerometerInterface.getjTextField4().getText());
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public static String ipAddress="192.168.254.255";
    public static int portNumber=5001;
    public static String fileName="";
    public static String line="";

    public static java.text.DecimalFormat decForm = new java.text.DecimalFormat("###.##");

}
