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 DynamicDataDemo_test extends JApplet implements ActionListener {
  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 = 1000;
  int delay;
  Timer timer;
  boolean frozen = false;
  ValueAxis axis;
  static final int ZOO_INIT =  20;//100;

  String user="manager";
  String psswrd="manager";
  //String db="merit";
  String db="smarthomes";
  
  String host="localhost";
  ResultSet result;
  String sqlCommand ="select m_item, datetime,  value  from  monitored "+
                     " where  ((NOW() - INTERVAL 12 HOUR)  <= datetime )" +
                           " AND ((NOW()) >= datetime )" +
                      " and  m_id =\'A062166112\' and m_item = \'tmp25\'"+
                      " order by datetime asc";
 String sqlCommand2 ="select m_item, datetime,  value  from  monitored "+
                    " where  ((NOW() - INTERVAL 12 HOUR)  <= datetime )" +
                     " AND ((NOW()) >= datetime )" +
                     " and  m_id =\'A062166112\' and m_item = \'hmd26\'"+
                     " order by datetime asc";
 String sqlCommand3 ="select m_item, datetime,  value  from  monitored "+
                     " where  ((NOW() - INTERVAL 12 HOUR)  <= datetime )" +
                    " AND ((NOW()) >= datetime )" +
                   " and  m_id =\'A062166112\' and m_item = \'tmp14\'"+
                  " 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){
    }
    date01ARR = new Date[100000];
    int k01=0;
    value01ARR = new double[100000];
    int j01=0;
    try{
      while(result.next()){
      //  System.out.print( result.getString("datetime") +" " +k01);
       date01ARR[k01++] = (Date) result.getObject("datetime");
        //System.out.print(result.getString( "value") +newline);
       value01ARR[j01++] = Double.parseDouble(result.getString("value"));
    }
    } catch(SQLException sqle){  System.out.print(sqle.getMessage()); }

///////////// data set 2      //////////////////////////////////
    SQLClient  sql02  = new SQLClient(user, psswrd,  host,db );
    sql02.setSqlStatement( sqlCommand2);
    sql02.go();
    while (sql02.sqlThread !=null){
    }
    result= sql02.getResultSet();
    while (sql02.sqlThread !=null){
    }
    date02ARR = new Date[100000];
    int k02=0;

    value02ARR = new double[100000];
    int j02=0;
    try{
       while(result.next()){
         //System.out.print( result.getString("datetime") +" "+ k02);
         date02ARR[k02++] = (Date) result.getObject("datetime");
         value02ARR[j02++] = Double.parseDouble(result.getString("value"));
         //System.out.println( " test " + date02ARR[k02--]);
       }
    } catch(SQLException sqle){  System.out.print(sqle.getMessage()); }

//////////////////

///////////// data set 3      //////////////////////////////////
    SQLClient  sql03  = new SQLClient(user, psswrd,  host,db );
    sql03.setSqlStatement( sqlCommand3);
    sql03.go();
    while (sql03.sqlThread !=null){
    }
    result= sql03.getResultSet();
    while (sql03.sqlThread !=null){
    }
    date03ARR = new Date[100000];
    int k03=0;

    value03ARR = new double[100000];
    int j03=0;
    try{
       while(result.next()){
         date03ARR[k03++] = (Date) result.getObject("datetime");
         value03ARR[j03++] = Double.parseDouble(result.getString("value"));

       }
    } catch(SQLException sqle){  System.out.print(sqle.getMessage()); }

//////////////////

    delay = 1000 / FPS_INIT;
    this.series01 = new TimeSeries("Indoor temprature", Millisecond.class);
    this.series02 = new TimeSeries("humidity", 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(10,10);
        //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(
            "Critical values"),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.NORTH); //SOUTH

        setContentPane(content);

        timer = new Timer(delay, this);
        //timer.setInitialDelay(0);
        timer.setInitialDelay(delay);
        timer.setCoalesce(true);

        axis.setFixedAutoRange(600000000.0/ZOO_INIT);
        drawProfile();
    //    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 boolean drawProfile() {
    boolean flag= true;
    Millisecond h01 ;
    Millisecond h02  ;
    Millisecond h03  ;

   while(flag){
    if( (date01ARR[i] !=null)&& (date02ARR[i] !=null) && (date03ARR[i] !=null) ){
       h01 = new Millisecond(date01ARR[i]);
       h02 = new Millisecond(date02ARR[i]);
       h03 = new Millisecond(date03ARR[i]);
    }
    else
      return true;

    Date d =new Date(2002,9, 8);

    if (value01ARR[i]==0.0 || value02ARR[i]==0.0) {
        stopAnimation();
    }
    else {
       if( i >1300){
         delay = 1;
         startAnimation();
         timer.setDelay(delay);
         flag=false;
         return true;

       }
      if (value01ARR[i]<20.0) {
        //File clipFile = new File("criticalValue.wav");
        //ClipPlayer cp = new ClipPlayer(clipFile, 0);
        textArea.setText(textArea.getText()+newline+"temperature bellow comfort zone : "+value01ARR[i]+" degC on "+date01ARR[i] );
      }
      if (value01ARR[i]<15.0) {
       //File clipFile = new File("criticalValue.wav");
       //ClipPlayer cp = new ClipPlayer(clipFile, 0);
       textArea.setText(textArea.getText()+newline+"Cold Alarm to be issued : "+value01ARR[i]+" degC on "+date01ARR[i] );
     }

    if (value02ARR[i]>50.0) {

      //File clipFile = new File("./sounds/criticalValue.wav");
      //ClipPlayer cp = new ClipPlayer(clipFile, 0);
      textArea.setText(textArea.getText()+newline+"Mould Risk Warning: "+value02ARR[i]+" degC on "+date02ARR[i] );
    }

    //Millisecond h01 = new Millisecond(date01ARR[i]);
    series01.add(h01, value01ARR[i]);
    // Millisecond h02 = new Millisecond(date02ARR[i]);
    series02.add(h02, value02ARR[i]);
    // Millisecond h02 = new Millisecond(date02ARR[i]);
    series03.add(h03, value03ARR[i]);
  }
  // System.out.println(i);
   i++;
  }
 return true;
  }

  public void actionPerformed(ActionEvent e) {

    if (value01ARR[i]==0.0 || value02ARR[i]==0.0  || value03ARR[i]==0.0) {
        stopAnimation();
    }
    else {
        Millisecond h01 = new Millisecond(date01ARR[i]);
        Millisecond h02 = new Millisecond(date02ARR[i]);
        Millisecond h03 = new Millisecond(date03ARR[i]);
        Date d =new Date(2002,9, 8);
       /*
       if( i > 1437){
         delay = 3000;
         timer.setDelay(delay);

       } */

      if (value01ARR[i]<20.0) {
        //File clipFile = new File("criticalValue.wav");
        //ClipPlayer cp = new ClipPlayer(clipFile, 0);
        textArea.setText(textArea.getText()+newline+"temperature bellow comfort zone : "+value01ARR[i]+" degC on "+date01ARR[i] );
      }
      if (value01ARR[i]<15.0) {
       //File clipFile = new File("criticalValue.wav");
       //ClipPlayer cp = new ClipPlayer(clipFile, 0);
       textArea.setText(textArea.getText()+newline+"Cold Alarm to be issued : "+value01ARR[i]+" degC on "+date01ARR[i] );
     }

    if (value02ARR[i]>50.0) {

      //File clipFile = new File("./sounds/criticalValue.wav");
      //ClipPlayer cp = new ClipPlayer(clipFile, 0);
      textArea.setText(textArea.getText()+newline+"Mould Risk Warning: "+value02ARR[i]+" degC on "+date02ARR[i] );
    }

    //Millisecond h01 = new Millisecond(date01ARR[i]);
    series01.add(h01, value01ARR[i]);
    // Millisecond h02 = new Millisecond(date02ARR[i]);
    series02.add(h02, value02ARR[i]);
    // Millisecond h02 = new Millisecond(date02ARR[i]);
    series03.add(h03, value03ARR[i]);
  }
 // System.out.println(i);
   i++;

  }

  public static void main(String[] args) {
    DynamicDataDemo_test demo = new DynamicDataDemo_test();
    demo.setVisible(true);
  }
}


