
import java.awt.CardLayout;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

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

/*
 * GUIFrame.java
 *
 * Created on 17-08-2011, 09:20:08 PM
 */

/**
 * Clase que crea el Frame principal de la GUI.
 * @author Manuel
 */


public class GUIFrame extends javax.swing.JFrame {

    /** Crea Frame principal. */
    public GUIFrame() {
        initComponents();
        ShowCardPanel("NonPanel");

        try {
            out = new PrintStream(FILENAME);
        }
        catch (FileNotFoundException f) {
        }
    }

    /** Metodo llamado por el costructor que inicializa elementos del Frame principal de la GUI.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        CardPanel = new javax.swing.JPanel();
        MainPanel = new javax.swing.JPanel();
        infoPanel1 = new InfoPanel();
        panelSolar1 = new PanelSolar();
        batteryPanel1 = new BatteryPanel();
        Logo = new javax.swing.JLabel();
        BG_Image = new javax.swing.JLabel();
        BG_BPanel = new javax.swing.JPanel();
        BG_SPanel = new javax.swing.JPanel();
        BG_SpPanel = new javax.swing.JPanel();
        MenuBar = new javax.swing.JMenuBar();
        FileMenu = new javax.swing.JMenu();
        ConfigMenu = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Usolem GUI");
        setBounds(new java.awt.Rectangle(450, 150, 0, 0));

        CardPanel.setBackground(new java.awt.Color(204, 51, 255));
        CardPanel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                CardPanelKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                CardPanelKeyReleased(evt);
            }
        });
        CardPanel.setLayout(new java.awt.CardLayout());

        MainPanel.setLayout(null);
        MainPanel.add(infoPanel1);
        infoPanel1.setBounds(35, 370, 260, 130);
        MainPanel.add(panelSolar1);
        panelSolar1.setBounds(715, 370, 260, 130);
        MainPanel.add(batteryPanel1);
        batteryPanel1.setBounds(20, 10, 260, 130);

        Logo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/logo.png"))); // NOI18N
        MainPanel.add(Logo);
        Logo.setBounds(330, 450, 350, 80);

        BG_Image.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/background.png"))); // NOI18N
        BG_Image.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        MainPanel.add(BG_Image);
        BG_Image.setBounds(0, 0, 1008, 540);

        CardPanel.add(MainPanel, "NonPanel");

        BG_BPanel.setBackground(new java.awt.Color(255, 255, 255));
        BG_BPanel.setLayout(new java.awt.BorderLayout());

        GBatteryPanel = new GraphPanel("Potencia aportada por Baterias");
        BG_BPanel.add(GBatteryPanel);

        CardPanel.add(BG_BPanel, "BG_BPanel");

        BG_SPanel.setBackground(new java.awt.Color(255, 255, 255));
        BG_SPanel.setLayout(new java.awt.BorderLayout());

        GSolarPanel = new GraphPanel("Potencia aportada por Panel Solar");
        BG_SPanel.add(GSolarPanel);

        CardPanel.add(BG_SPanel, "BG_SPanel");

        BG_SpPanel.setBackground(new java.awt.Color(255, 255, 255));
        BG_SpPanel.setLayout(new java.awt.BorderLayout());

        GSpeedPanel = new GraphPanel("Velocidad del vehículo");
        BG_SpPanel.add(GSpeedPanel);

        CardPanel.add(BG_SpPanel, "BG_SpPanel");

        getContentPane().add(CardPanel, java.awt.BorderLayout.CENTER);

        FileMenu.setText("File");
        MenuBar.add(FileMenu);

        ConfigMenu.setText("Config");
        ConfigMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ConfigMenuMouseClicked(evt);
            }
        });
        MenuBar.add(ConfigMenu);

        setJMenuBar(MenuBar);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-1024)/2, (screenSize.height-600)/2, 1024, 600);
    }// </editor-fold>//GEN-END:initComponents

    private void ConfigMenuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ConfigMenuMouseClicked
        ConfigCOM.setVisible(true);
    }//GEN-LAST:event_ConfigMenuMouseClicked

    private void CardPanelKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CardPanelKeyPressed
        // TODO add your handling code here:
//        if(evt.getKeyCode() == KeyEvent.VK_UP)
//            ShowCardPanel("BG_BPanel");
//        if(evt.getKeyCode() == KeyEvent.VK_LEFT)
//            ShowCardPanel("BG_SPanel");
//        if(evt.getKeyCode() == KeyEvent.VK_RIGHT)
//            ShowCardPanel("BG_SpPanel");
    }//GEN-LAST:event_CardPanelKeyPressed

    private void CardPanelKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CardPanelKeyReleased
        // TODO add your handling code here:
//        if( evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_LEFT ||
//            evt.getKeyCode() == KeyEvent.VK_RIGHT )
//                ShowCardPanel("NonPanel");
    }//GEN-LAST:event_CardPanelKeyReleased


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel BG_BPanel;
    private javax.swing.JLabel BG_Image;
    private javax.swing.JPanel BG_SPanel;
    private javax.swing.JPanel BG_SpPanel;
    private javax.swing.JPanel CardPanel;
    private javax.swing.JMenu ConfigMenu;
    private javax.swing.JMenu FileMenu;
    private javax.swing.JLabel Logo;
    private javax.swing.JPanel MainPanel;
    private javax.swing.JMenuBar MenuBar;
    private BatteryPanel batteryPanel1;
    private InfoPanel infoPanel1;
    private PanelSolar panelSolar1;
    // End of variables declaration//GEN-END:variables

    final static String FILENAME = "gps.txt";
    
    private ConfigCOMFrame ConfigCOM  = null;
    private Communicator communicator = null;
    private Scanner data = null;
    private PrintStream out;

    // Valores medidos desde Arduino
    private float SolarPower;
    private float BatteryPower;
    private float TotalPower;
    private int SolarState;
    private int BatteryState;
    private int BrakeState;
    private int BatteryLevel;
    private int PanelDisplayed;
    private boolean SolarConnected   = false;
    private boolean BatteryConnected = false;
    private boolean BrakeConnected   = false;
    private float SolarPercent;
    private float BatteryPercent;
    private float Speed;
    private String GPS_Data;

    // Paneles Graficos
    private GraphPanel GBatteryPanel = null;
    private GraphPanel GSolarPanel   = null;
    private GraphPanel GSpeedPanel   = null;

    /**
	* Asigna el Frame de configuracion de puerto COM.
	* @param ConfigCOM Frame a asignar en el Frame principal de GUI 
	*/
	public void setConfigCOMPanel(ConfigCOMFrame ConfigCOM) {
        this.ConfigCOM = ConfigCOM;
    }
	
	/**
	* Retorna el Frame ConfigCOM
	* @return Frame que maneja la configuracion de los puertos COM
	*/
    public ConfigCOMFrame getConfigCOMPanel() {
        return ConfigCOM;
    }
	
	/**
	* Asigna objeto communicator del GUIFrame
	* @param communicator objeto que maneja la comunicacion serial.
	*/
    public void setCommunicator(Communicator communicator) {
        this.communicator = communicator;
    }
	
	/**
	* Retorna objeto communicator del GUIFrame
	* @return objeto que maneja la comunicacion serial perteneciente al GUIFrame
	*/
    public Communicator getCommunicator() {
        return communicator;
    }
	
	/** 
	* Obtiene variables desde microcontrolador.
	* @param SerialData Palabra que contiene valores delimitados por el caracter ";".
	*/
    public void setVariables(String SerialData) {
        // Lectura de variables
        data = new Scanner(SerialData).useDelimiter(";");

        SolarPower   = Float.parseFloat(data.next());
        BatteryPower = Float.parseFloat(data.next());
        SolarState   = data.nextInt();
        BatteryState = data.nextInt();
        BatteryLevel = data.nextInt();
        Speed = Float.parseFloat(data.next());
        BrakeState = data.nextInt();
        GPS_Data = data.next();
        PanelDisplayed = data.nextInt();

        // Guardado de datos del GPS en archivo
        out.println(GPS_Data);

        // Calculos de porcentajes de potencias.
        if (BatteryPower > 0) {
            TotalPower = BatteryPower + SolarPower;
            BatteryPercent = (BatteryPower *100) / TotalPower;
            SolarPercent   = (SolarPower *100) / TotalPower;
        }
        else {
            BatteryPercent = 0.0f;
            SolarPercent   = 0.0f;
        }

        // Transformacion de int a boolean para interruptores
        if (SolarState == 0)
            BatteryConnected = false;
        else
            BatteryConnected = true;

        if (BatteryState == 0)
            SolarConnected = false;
        else
            SolarConnected = true;
        
        if (BrakeState == 0)
            BrakeConnected = false;
        else
            BrakeConnected = true;

        // Actualizacion de datos en paneles
        panelSolar1.updateValues(SolarPower, SolarPercent, SolarConnected);
        batteryPanel1.updateValues(BatteryPower, BatteryPercent, BatteryConnected, BatteryLevel);
        infoPanel1.updateValues(TotalPower,Speed,BrakeConnected);
        updateGraphPanels();

        // Eleccion de panel a mostrar
        switch (PanelDisplayed) {
            case 0: ShowCardPanel("NonPanel");
                    break;
            case 1: ShowCardPanel("BG_SPanel");
                    break;
            case 2: ShowCardPanel("BG_BPanel");
                    break;
            case 3: ShowCardPanel("BG_SpPanel");
                    break;
        }
    }
	
	/**
	* Muestra panel con graficos 2D
	*/
    private void ShowCardPanel(String string) {
        CardLayout card = (CardLayout) CardPanel.getLayout();
        card.show(CardPanel,string);
    }
	
	/**
	* Asigna el foco a los paneles graficos
	*/
    public void setfocustoPanels() {
        CardPanel.requestFocusInWindow();
    }
	
	/**
	* Actualiza valores mostrados por todos los graficos
	*/
    private void updateGraphPanels() {
        GBatteryPanel.updateGraph(BatteryPercent);
        GSolarPanel.updateGraph(SolarPercent);
        GSpeedPanel.updateGraph(Speed);
    }
}
