import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.Date;
import java.util.Calendar;
import java.util.Locale;

import com.jrefinery.data.*;
import com.jrefinery.data.TimeSeriesCollection;
import com.jrefinery.data.Millisecond;
import com.jrefinery.data.Hour;
import com.jrefinery.ui.ApplicationFrame;
import com.jrefinery.chart.ChartFactory;
import com.jrefinery.chart.JFreeChart;
import com.jrefinery.chart.ChartPanel;
import com.jrefinery.chart.axis.ValueAxis;
import com.jrefinery.chart.plot.XYPlot;
import com.jrefinery.ui.RefineryUtilities;
import	javax.sound.sampled.Clip;

import java.sql.*;
import entrak.sqlclient.*;

public class DynamicDataViewer extends JApplet implements ActionListener {
 String[] mid01ARR ;
  double[] value01ARR;
  Date[] date01ARR;
  double[] value02ARR;
  Date[] date02ARR;
  double[] value03ARR;
  Date[] date03ARR;
  private TimeSeries series01;
  private TimeSeries series02;
  private TimeSeries series03;

  int i=0;
  JTextArea textArea;
  private String newline = "\n";
  static final int FPS_INIT = 10;
  int delay;
  Timer timer;
  boolean frozen = false;
  ValueAxis axis;
  static final int ZOO_INIT =  300;//100;

  String user="manager";
  String psswrd="manager";
 
  String db="smarthomes";
 
  String host="localhost";
  ResultSet result;
  String sqlCommand ="select entity.name,  datetime,  value  from  entity, monitored "+
                     " where  entity.ref=monitored.m_id and ((NOW() - INTERVAL 10 HOUR)  <= datetime )" +
                           " AND ((NOW()) >= datetime )" +
                      " and entity.district like \'%\' and m_item LIKE \'tmp%\'"+
                      " order by datetime asc";

  String sqlCommand2 ="select m_item, datetime,  value  from  monitored "+
                       " where  ((NOW() - INTERVAL 3 HOUR)  <= datetime )" +
                         " AND ((NOW()) >= datetime )" +
                         " and  m_id =\'A062567811\' and m_item = \'tmp53\'"+
                        " order by datetime asc";

  public void init() {
  //////////////////// dataset 1 ///////////////////////////////
    SQLClient  sql  = new SQLClient(user, psswrd,  host,db );
    sql.setSqlStatement( sqlCommand);
    sql.go();
    while (sql.sqlThread !=null){
    }
    result= sql.getResultSet();
    while (sql.sqlThread !=null){
    }
    mid01ARR = new String[100000];
    int n01=0;
    date01ARR = new Date[100000];
    int k01=0;
    value01ARR = new double[100000];
    int j01=0;
    try{
      while(result.next()){
        //System.out.print( result.getString("datetime") +" ");
        mid01ARR[n01++] =(String) result.getObject("entity.name");
       date01ARR[k01++] = (Date) result.getObject("datetime");
       //System.out.println( "here here "  + n01 +mid01ARR[n01-1]+ " "+date01ARR[k01-1] );
       value01ARR[j01++] = Double.parseDouble(result.getString("value"));
    }
    } catch(SQLException sqle){  System.out.print(sqle.getMessage()); }


    delay = 1000 / FPS_INIT;
    this.series01 = new TimeSeries(" Temprature", Millisecond.class);
    //this.series02 = new TimeSeries("Outdoor Temperature", Millisecond.class);
    //this.series03 = new TimeSeries("Outdoor temprature", Millisecond.class);

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series01);
    //dataset.addSeries(series02);
    //dataset.addSeries(series03);

    JFreeChart chart = ChartFactory.createTimeSeriesChart("","Time", "degC",dataset, true, true, false);
    XYPlot plot = chart.getXYPlot();
    axis = plot.getDomainAxis();
    axis.setAutoRange(true);
    axis.setFixedAutoRange(600000000.0);  //initial zoom

        JPanel content = new JPanel(new BorderLayout());

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        chartPanel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(
            "Evironemental Condition Profile"),BorderFactory.createEmptyBorder(0,0,0,0)),
            chartPanel.getBorder()));

        content.add(chartPanel, BorderLayout.CENTER);

        textArea = new JTextArea(30,30);
        //textArea.setForeground(Color.red);
        textArea.setFont(new Font("Serif", Font.BOLD, 12));
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane StextArea = new JScrollPane(textArea);
        StextArea.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(
            "Entity at out of range "),BorderFactory.createEmptyBorder(0,0,0,0)),
            StextArea.getBorder()));
        content.add(StextArea, BorderLayout.EAST);


        JButton arrangeVisitorB = new JButton("Arrange visitor");
        JButton nurseB = new JButton("Nurse");
        JButton firefighterB = new JButton("Firefighter");
        JPanel buttonsP = new JPanel();

        buttonsP.add(arrangeVisitorB);
        buttonsP.add(nurseB);
        buttonsP.add(firefighterB);

        content.add(buttonsP, BorderLayout.SOUTH); //SOUT
        setContentPane(content);
        timer = new Timer(delay, this);
        timer.setInitialDelay(delay);
        axis.setFixedAutoRange(600000000.0/ZOO_INIT);
        startAnimation();
    }
    class SliderListener implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider)e.getSource();
            if (!source.getValueIsAdjusting()) {
                int fps = (int)source.getValue();
                if (fps == 0) {
                    if (!frozen) stopAnimation();
                } else {
                  delay = 1000 / fps;
                    timer.setDelay(delay);
                    if (frozen) startAnimation();
                }
            }
        }
    }

    class SliderListener1 implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider)e.getSource();
            if (!source.getValueIsAdjusting()) {
                int fps = (int)source.getValue();
                if (fps == 0) {
                    if (!frozen) stopAnimation();
                } else {
                    axis.setFixedAutoRange(600000000.0/fps);
                    if (frozen) startAnimation();
                }
            }
        }
    }
  public void startAnimation() {
     timer.start();
     frozen = false;
   }

  public void stopAnimation() {
        timer.stop();
        frozen = true;
  }


  public void actionPerformed(ActionEvent e) {
    Millisecond h01 = new Millisecond(date01ARR[i]);

    if (value01ARR[i]==0.0    ) {
        stopAnimation();
       //System.out.println("here");
    }
    else {
      Date d =new Date(2002,9, 8);

       if( i > 10){
         delay =400;
         timer.setDelay(delay);
       }

      if (value01ARR[i]< 12.0 && value01ARR[i]> -1) {
        textArea.setForeground(Color.RED);
        textArea.setText(textArea.getText()+newline+ mid01ARR[i]+ ": Cold Alarm activated : "+value01ARR[i]+" degC on "+date01ARR[i] );
        series01.addOrUpdate(h01, new Double(value01ARR[i]));
        new ClipPlayer(new File( "criticalValue.wav"), 3);
      }
      else if (value01ARR[i] > 31.0 ) {
        textArea.setForeground(Color.RED);
        textArea.setText(textArea.getText()+newline+ mid01ARR[i]+ ": Over heating : "+value01ARR[i]+" degC on "+date01ARR[i] );
           series01.addOrUpdate(h01, new Double(value01ARR[i]));
           new ClipPlayer(new File( "criticalValue.wav"), 1);
     }
     else if (value01ARR[i] > -10 )
         series01.addOrUpdate(h01, new Double(value01ARR[i]));
  }
   i++;
  }
  public static void main(String[] args) {
    DynamicDataViewer demo = new DynamicDataViewer();
    demo.setVisible(true);
  }
}


