<!-- Author : Jagbir Singh -->
<!-- Debug : Amanbir Singh -->
<!-- Tested : Ajinkya Bilolikar , Swapnil Sarode -->

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.ArrayList"%>

<%@ page language="java" import="java.sql.*, javax.sql.DataSource, javax.naming.*" errorPage="" %>

<%

String startDate = request.getParameter("StartDate");		//receiving start time
String endDate = request.getParameter("EndDate");			//receiving end time
String userId = request.getParameter("userId");				//getting user Id of the of the user whose data to be displayed


if((startDate==null || startDate.equals("") || endDate == null) || endDate.equals("")){

	pageContext.forward("errCalender.jsp");		//if startTime or End Time is null return error
	
	return;
}

if(startDate.charAt(17)!='A')			//converting time string into DB DateTime format
{
	int i = Character.getNumericValue(startDate.charAt(11));
	int j = Character.getNumericValue(startDate.charAt(12));
	if(j<2 || i==0){
	int hr = 12 + j + 10*i;
	String hour = Integer.toString(hr);
	String space = " ";
	hour = space.concat(hour);
	String hh = startDate.substring(10, 13);
		startDate = startDate.replace(hh, hour);
	}
}

startDate = startDate.replace(" AM", ":00");
startDate = startDate.replace(" PM", ":00");
startDate = startDate.concat(".000");

if(endDate.charAt(17)!='A')				//converting endTime into DB dateTime format
{
	int i = Character.getNumericValue(endDate.charAt(11));
	int j = Character.getNumericValue(endDate.charAt(12));
	if(j<2 || i==0){
	int hr = 12 + j + 10*i;
	String hour = Integer.toString(hr);
	String space = " ";
	hour = space.concat(hour);
	String hh = endDate.substring(10, 13);
	endDate = endDate.replace(hh, hour);
	}
}
endDate = endDate.replace(" AM", ":00");
endDate = endDate.replace(" PM", ":00");
endDate = endDate.concat(".000");

DataSource pool;
Connection conn = null;
PreparedStatement pstmt = null;
PreparedStatement pstmt2 = null;
PreparedStatement pstmt3 = null;
String spclQuery = null;
ArrayList<String> totalEnergy  = new ArrayList<String>();		//for getting totalEnergy component from DB
ArrayList<String> actvEnergy  = new ArrayList<String>();		//for calculating Active Energy component
ArrayList<String> numsteps = new ArrayList<String>();			//for getting number of steps component from DB
ArrayList<String> dataDate = new ArrayList<String>();			//for getting date of Data component from DB
ArrayList<String> dateLabel = new ArrayList<String>();			//for converting date into the format to be displayed
ArrayList<String> numLabel = new ArrayList< String>();			//for storing calculated number of steps
ArrayList<String> sleepStart = new ArrayList< String>();		//for calculating sleep start time
ArrayList<String> sleepEnd = new ArrayList< String>();			//for caculating sleep end time
ArrayList<Integer> numSleepHrs = new ArrayList<Integer>();		//for total number of sleep hours over one iteration
ArrayList<String> lyingStart = new ArrayList< String>();		//for calculating lying down start time
ArrayList<String> lyingEnd = new ArrayList< String>();			//for caculating lying down end time
ArrayList<Integer> numLyingHrs = new ArrayList<Integer>();		//total number of lying down hours over one iteration
ArrayList<Integer> varEnergy = new ArrayList<Integer>();		//for calculating various types of energy expenditures
double finEnergy = 0;						//total Final Energy Expenditure
double actvEner =0;							//for total active Energy
double sedEnergy =0;						//for sedentary Energy
double modEnergy =0;						//for total moderate energy
double vigEnergy =0;						//total vigrous Energy Expenditure
double veryVigEnergy =0;					//total very vigrous Energy Expenditure
int sedPerEnergy = 0;						//percentage of sedentary energy Expenditure
int modPerEnergy = 0;						//percentage of moderate energy Expenditure
int vigPerEnergy = 0;						//percentage of vigrous energy Expenditure
int veryVigPerEnergy = 0;					//percentage of very vigrous energy Expenditure
String dateLabelStr = "";					
String sleepStartStr = "";
String lyingStartStr = "";
int phyHrs =0, sedHrs=0, modHrs =0, vigHrs = 0, veryVigHrs =0, totalDur = 0;
int elements = 0;

ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
int j=0;
try{
	InitialContext ctx = new InitialContext();
	pool = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
	if (pool == null)
        throw new SQLException("Unknown DataSource 'jdbc/TestDB'");
	conn = pool.getConnection();
		//making DB connection pool
	
		
		spclQuery = "SELECT totEnerExp, numSteps, dataOfData, physActivityDur, sedenTary, modActivity, vigrousActivity, veryVigActivity  from dataInfo where dataOfData > ? and dataOfData < ? and userId = ?";
	       pstmt = conn.prepareStatement(spclQuery);   
	       	pstmt.setString(1, startDate);
	       	pstmt.setString(2, endDate);
	       	pstmt.setString(3, userId);
	        rs = pstmt.executeQuery();
	       
	        String query2 = "SELECT totEnerExp from dataInfo where dataOfData > ? and dataOfData < ? and physActivityDur = 1 and userId = ?";
	        pstmt2 = conn.prepareStatement(query2);   
	       	pstmt2.setString(1, startDate);
	       	pstmt2.setString(2, endDate);
	       	pstmt2.setString(3, userId);
	       	rs2 = pstmt2.executeQuery();
	        
	        String query3 = "SELECT sleepTime, lyingDownTime, dataOfData from dataInfo where userId = ?";
	        pstmt3 = conn.prepareStatement(query3);   
	       	pstmt3.setString(1, userId);
	        rs3 = pstmt3.executeQuery();
	        
	       while(rs.next())
	       	{
	 	
	    		totalEnergy.add(rs.getString("totEnerExp"));
	    	
	    		numsteps.add(rs.getString("numSteps"));
	    		
    		
    		String data = rs.getString("dataOfData");
    		data.replace(' ', '_');
  
    		dataDate.add(data);
    		if(rs.getInt("physActivityDur")==1){
    			
    			phyHrs++;
    			
    		}
			if(rs.getInt("sedenTary")==1){
    			
    			sedHrs++;
    			sedEnergy = sedEnergy + Double.parseDouble(totalEnergy.get(elements));
    		}
			if(rs.getInt("modActivity")==1){
		
			modHrs++;
			modEnergy = modEnergy + Double.parseDouble(totalEnergy.get(elements));
			}
			
			if(rs.getInt("vigrousActivity")==1){
			vigHrs++;
			vigEnergy = vigEnergy + Double.parseDouble(totalEnergy.get(elements));
			}
			
			if(rs.getInt("veryVigActivity")==1){
			veryVigHrs++;
			veryVigEnergy = veryVigEnergy + Double.parseDouble(totalEnergy.get(elements));
			}
    		
			totalDur = phyHrs + sedHrs;
			elements++;
   	    		  		
	    	 }
	       int k = 0;
	       while(rs2.next()){
	    	   
	    	   actvEnergy.add(rs2.getString("totEnerExp"));
	    	    actvEner = actvEner + Double.parseDouble(actvEnergy.get(k));
	    	   k++;
	       }

			elements = 0;
	       elements = totalEnergy.size();

	        k = 0;
	       while(elements != 1){
	    	   finEnergy = finEnergy + Double.parseDouble(totalEnergy.get(k));
	    	   	elements--;
	    	   	k++;
	       }
	       
	   	k =1;
		int flag = 0, flag2=0, y = 1;
		while(rs3.next()){
			
			if(rs3.getInt("sleepTime")==1 && flag==0)
			{
				sleepStart.add(rs3.getString("dataOfData"));
				flag = 1;
			}
			if(flag == 1){
				k++;
			}
			if(rs3.getInt("sleepTime")==0 && flag ==1 && k >= 20){		//calculating sleep duration with minimum 20 minutes of sleep duration
				sleepEnd.add(rs3.getString("dataOfData"));
				flag = 0;
				numSleepHrs.add(k);
				k =1;
			}
			
			if(rs3.getInt("lyingDownTime")==1 && flag2==0 && rs3.getInt("sleepTime")==0 )
			{
				lyingStart.add(rs3.getString("dataOfData"));
				flag2 = 1;
			}
			if(flag2 == 1){
				y++;
			}
			if(((rs3.getInt("lyingDownTime")==0 && flag2 ==1) || rs3.getInt("sleepTime")==1) && y > 2){		// caculating lying down duration per 2 minutes
				lyingEnd.add(rs3.getString("dataOfData"));
				flag2 = 0;
				numLyingHrs.add(y);
				y =1;
			}
			
		}
		
		for(int i = 0; i<sleepStart.size(); i++){		//converted into a format to be used for displaying graphs
			if(i == 0){
				sleepStartStr = "'"+sleepStart.get(i)+"'";
			} else {
				sleepStartStr = sleepStartStr+", '"+sleepStart.get(i)+"'";
			}
		}
		
		for(int i = 0; i<lyingStart.size(); i++){
			if(i == 0){
				lyingStartStr = "'"+lyingStart.get(i)+"'";
			} else {
				lyingStartStr = lyingStartStr+", '"+lyingStart.get(i)+"'";
			}
		}
			//calculating various percentages expenditure for different types of energy
			
	       sedPerEnergy = ((int)((sedEnergy/finEnergy)*100));
	       
	       modPerEnergy = ((int)((modEnergy/finEnergy)*100));
	       vigPerEnergy = ((int)((vigEnergy/finEnergy)*100));
	       veryVigPerEnergy = ((int)((veryVigEnergy/finEnergy)*100));
	       
	       varEnergy.add(0, veryVigPerEnergy);
	       varEnergy.add(1, sedPerEnergy);
	       varEnergy.add(2, modPerEnergy);
	       varEnergy.add(3, vigPerEnergy);
	      
	       
int size = dataDate.size();
int start = size/6;				//dividing total time into 6 equal durations
	
	String index;
	  index = dataDate.get(0);
	  index = index.toString();
      		
	dateLabel.add(index);
	
	index = dataDate.get(start);
	
	dateLabel.add(index);
	
	index = dataDate.get(2*start);
	
	dateLabel.add(index);

	index = dataDate.get(3*start);
		dateLabel.add(index);

	index = dataDate.get(4*start);
	
	dateLabel.add(index);

	index = dataDate.get(size -1);
	
	dateLabel.add(index);

	float num =0;
	String steps;
	
	for(int i =0; i<6; i++){
		
		num =0;
		for( j=0 + (i*start) ; j<start + (i*start); j++){
			 steps = numsteps.get(j);
			
			 num = num + Float.parseFloat(steps);
			
		}
	steps = Float.toString(num);
		numLabel.add(steps);
		
	}
	
	for(int i = 0; i<dateLabel.size(); i++){
		if(i == 0){
			dateLabelStr = "'"+dateLabel.get(i)+"'";
		} else {
			dateLabelStr = dateLabelStr+", '"+dateLabel.get(i)+"'";
		}
	}
	rs.close();
    pstmt.close();
    rs2.close();
    pstmt2.close();
    rs3.close();
    pstmt3.close();
    conn.close();  
    
    
	
}catch(SQLException se){
	se.printStackTrace();
}catch(Exception e){
    //Handle errors for Class.forName
    e.printStackTrace();
 }finally{
    //finally block used to close resources
    try{
       if(pstmt!=null)
          pstmt.close();
    }catch(SQLException se2){
    }// nothing we can do
    try{
       if(conn!=null)
       conn.close();
    }catch(SQLException se){
       se.printStackTrace();
    }//end finally try
 } //end try


%>

<html>
<head>
    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />
    
    <script type="text/javascript" src="libraries/RGraph.common.core.js" ></script>
    <script type="text/javascript" src="libraries/RGraph.common.dynamic.js" ></script>
    <script type="text/javascript" src="libraries/RGraph.common.effects.js" ></script>
    <script type="text/javascript" src="libraries/RGraph.common.tooltips.js" ></script>
    <script type="text/javascript" src="libraries/RGraph.bar.js" ></script>
    <script type="text/javascript" src="libraries/RGraph.pie.js" ></script>
    <script src="libraries/RGraph.line.js" ></script>
    <script src="libraries/RGraph.meter.js" ></script>
    <script src="libraries/RGraph.meter.js" ></script>
    <!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]-->
    
    <title>Graphical Representation</title>
</head>
<body>

<form name="home" " action="welcome.jsp">
<input type="image" src="home.jpg" alt="Submit" align="left" width="70" height="60">
</form>

<form name="logout" " action="logout.jsp">
<input type="image" src="logout.jpg" alt="Submit" align="right" width="60" height="60">
</form>

<form name="statistics" " action="statistics.jsp">
<input type = "hidden" value="<%=userId%>" name="userId">
<input type = "hidden" value="<%=startDate%>" name="startDate">
<input type = "hidden" value="<%=endDate%>" name="endDate">
<input type="image" src="graph.jpg" alt="Submit" align="left" width="80" height="80">
</form>
        
    <h2>Graphical Representation from <%=startDate%> to <%=endDate%></h2>
    
    <p>
    </p>
    <br><br><br>
<h3>Number of Steps</h3>
    <canvas id="cvs" width="1200" height="800">[No canvas support]</canvas>

    <script>
        window.onload = function ()
        {
            var bar8 = new RGraph.Bar('cvs', <%=numLabel.toString()%>);
            bar8.Set('chart.labels',[<%=dateLabelStr%>]);
            bar8.Set('chart.tooltips', function (index) {var label = <%=numLabel.toString()%>[index];return '<h2 style="text-align: center">' + label + '</h2><canvas id="tooltip_canvas" width="250" height="110"></canvas>';});
            RGraph.Effects.Bar.Grow(bar8);
            bar8.Set('chart.text.angle', 45);
            bar8.Set('chart.color',['green']);
            bar8.Set('chart.variant', '3d');
            bar8.Set('chart.text.size', 10);
            bar8.Set('chart.gutter.bottom', 200);
            bar8.Set('chart.gutter.left',55);
            bar8.Set('chart.gutter.top',60)

    
            DrawGraph();
            DrawMeter();
            DrawMeter2();
            DrawMeter3();
            DrawPie();
            DrawSleepBar();
            DrawLyingBar();
        }
    </script>


<h3> Energy in Calories per minute</h3>
 <canvas id="cvs1" width="1200" height="400">[No canvas support]</canvas>
    
    <script>
       

        function DrawGraph ()
        {
            
				 var line = new RGraph.Line('cvs1', <%=totalEnergy.toString()%> );
            line.Set('chart.labels', [<%=dateLabelStr%>]);
            line.Set('chart.linewidth', 2);
            line.Set('chart.colors.alternate', true);
            line.Set('chart.colors', [['red','black']]);
            line.Set('chart.gutter.left',70);
            line.Set('chart.gutter.right',80);
            line.Draw();

        }

    </script>

<h3>Total Energy and Active Energy in Calories</h3>
  <canvas id="cvs2" width="600" height="400">[No canvas support]</canvas>
    
    <script>
        function DrawMeter ()
        {
            var meter = new RGraph.Meter('cvs2', 0, <%=2*finEnergy%>, <%=finEnergy%>);
            meter.Set('chart.units.post', 'C');
              meter.Set('chart.red.start', 0);
              meter.Set('chart.red.end', 0);
              meter.Set('chart.yellow.start', 0);
              meter.Set('chart.yellow.end', 0);
            meter.Set('chart.green.start', 00);
            meter.Set('chart.green.end', <%=2*finEnergy%>);
            meter.Draw();
        }
    </script>
 
<canvas id="cvs3" width="600" height="400">[No canvas support]</canvas>
    
    <script>
        function DrawMeter2 ()
        {
            var meter = new RGraph.Meter('cvs3', 0, <%=finEnergy%>, <%=actvEner%>);
            meter.Set('chart.units.post', 'C');
              meter.Set('chart.red.start', 0);
              meter.Set('chart.red.end', 0);
              meter.Set('chart.yellow.start', 0);
              meter.Set('chart.yellow.end', 0);
            meter.Set('chart.green.start', 00);
            meter.Set('chart.green.end', <%=finEnergy%>);
            meter.Draw();
        }
    </script>
    
<h3>Duration in Hours for physical Activity</h3>
<canvas id="cvs4" width="400" height="200">[No canvas support]</canvas>

        <script>
        function DrawMeter3()
        {
            meter = new RGraph.Meter('cvs4', 0,24,<%=phyHrs/60%>);
            meter.Set('chart.border', false);
            meter.Set('chart.tickmarks.small.num', 0);
            meter.Set('chart.tickmarks.big.num', 0);
            meter.Set('chart.segment.radius.start', 140);
            meter.Set('chart.text.size', 20);
            meter.Set('chart.colors.ranges', [
                                              [0,40,'Gradient(#0c0:#cfc:#0c0)'],
                                              [40,80,'Gradient(yellow:#ffc:yellow)'],
                                              [80,100,'Gradient(red:#fcc:red)']
                                             ]);
            meter.Set('chart.needle.radius', 110);
            meter.Draw();
        }

        </script>


<h3>Percentage Duration for different Physical activities</h3>
<canvas id="cvs5" width="450" height="300">[No canvas support]</canvas>
    
    <script>
    	function DrawPie()
    	{
        var pie1 = new RGraph.Pie('cvs5',<%=varEnergy.toString()%>);
        pie1.Set('chart.radius', 100);
        pie1.Set('chart.tooltips', ['<%=veryVigEnergy%> C', '<%=sedEnergy%> C', '<%=modEnergy%> C', '<%=vigEnergy%> C']);
        pie1.Set('chart.labels', ['VeryVigrous=<%=veryVigPerEnergy%>%','Sedentary=<%=sedPerEnergy%>%', 'Moderate=<%=modPerEnergy%>%', 'Vigrous=<%=vigPerEnergy%>%']);
        pie1.Set('chart.strokestyle', 'white');
        pie1.Set('chart.linewidth', 10);
        pie1.Set('chart.shadow', true);
        pie1.Set('chart.shadow.blur', 10);
        pie1.Set('chart.shadow.offsetx', 0);
        pie1.Set('chart.shadow.offsety', 0);
        pie1.Set('chart.shadow.color', '#000');
        pie1.Set('chart.text.color', '#999');
        
        var explode = 20;

        function myExplode (obj)
        {
            window.__pie__ = pie1;

            for (var i=0; i<obj.data.length; ++i) {
                setTimeout('window.__pie__.Explode('+i+',10)', i * 50);
            }
        }

        if (RGraph.isOld()) {
            pie1.Draw();
        
        } else if (navigator.userAgent.toLowerCase().indexOf('firefox') >= 0) {
            RGraph.Effects.Pie.RoundRobin(pie1);
        
        } else {
            /**
            * The RoundRobin callback initiates the exploding
            */

            RGraph.Effects.Pie.RoundRobin(pie1, null, myExplode);
            RGraph.Effects.Pie.Implode(pie1);
        }
    }
    </script>


<h3>Sleep Duration in Minutes</h3>
<canvas id="cvs6" width="1000" height="700">[No canvas support]</canvas>
    <script>
    function DrawSleepBar(){
        var bar = new RGraph.Bar('cvs6', <%=numSleepHrs%>);
        bar.Set('chart.labels', [<%=sleepStartStr%>]);
        bar.Set('chart.tooltips', function (index) {var label = <%=numSleepHrs%>[index];return '<h4 style="text-align: center">' + label + '</h4><canvas id="tooltip_canvas" width="50" height="25"></canvas>';});
        bar.Set('chart.colors.sequential', true);
        bar.Set('chart.shadow', true);
        bar.Set('chart.text.angle', 45);
        bar.Set('chart.shadow.color', '#ccc');
        bar.Set('chart.variant', '3d');
        bar.Set('chart.gutter.bottom', 200);
        bar.Set('chart.gutter.left',90);
        bar.Draw();
        
        /**
        * Now the chart has been drawn use the coords to create some appropriate gradients
        */
        for (var i=0,colors=[]; i<bar.coords.length; ++i) {
        
            var x = bar.coords[i][0];
            var y = bar.coords[i][1];
            var w = bar.coords[i][0] + bar.coords[i][2];
            var h = bar.coords[i][1];

            colors[i] = RGraph.LinearGradient(bar, x, y, w, h, '#c00', 'red')
        }

        bar.Set('chart.colors', colors);
        RGraph.Clear(bar.canvas);
        RGraph.Redraw();
    }
    </script>
    
    
<h3>Lying Time Duration in minutes</h3>
<canvas id="cvs7" width="2000" height="700">[No canvas support]</canvas>

    <script>
    function DrawLyingBar(){
        var bar = new RGraph.Bar('cvs7', <%=numLyingHrs%>);
        bar.Set('chart.labels', [<%=lyingStartStr%>]);
        bar.Set('chart.tooltips', function (index) {var label = <%=numLyingHrs%>[index];return '<h4 style="text-align: center">' + label + '</h4><canvas id="tooltip_canvas" width="50" height="25"></canvas>';});
        bar.Set('chart.colors.sequential', true);
        bar.Set('chart.text.angle', 45);
        bar.Set('chart.shadow', true);
        bar.Set('chart.shadow.color', '#ccc');
        bar.Set('chart.variant', '3d');
        //bar.Set('hmargin.grouped', 1);
        bar.Set('chart.gutter.bottom', 200);
        bar.Set('chart.gutter.left',90);
        bar.Draw();
        
        /**
        * Now the chart has been drawn use the coords to create some appropriate gradients
        */
        for (var i=0,colors=[]; i<bar.coords.length; ++i) {
        
            var x = bar.coords[i][0];
            var y = bar.coords[i][1];
            var w = bar.coords[i][0] + bar.coords[i][2];
            var h = bar.coords[i][1];

            colors[i] = RGraph.LinearGradient(bar, x, y, w, h, '#c00', 'red')
        }

        bar.Set('chart.colors', colors);
        RGraph.Clear(bar.canvas);
        RGraph.Redraw();
    }
    </script>

</body>
</html>
