﻿# -*- coding: utf-8 -*-
import sys
import os


def CreateHtml(tableId, dataType, fPath, rows, titles, pos):
    logstr = ""
    chart_table = ""
    series = {}
    minTick = 5
    
    if len(rows) != 0:
        # convert the data into a table
        data = []
        xaxis = []
        periodRain = str(rows[-1][4]-rows[0][4])
        selectedPeriod = str(rows[0][0][:-3])+' - '+str(rows[-1][0][:-3])        
        r_start = rows[0][4]
        r_prev = 0
        bFirstDone = False
        for row in rows:
            r_tmp = row[4]
            t_tmp = row[0].split(' ')[1].split(':')
            d_tmp = row[0].split(' ')[0].split('-')
            if row[4] == r_start and not bFirstDone: #if first row
                bFirstDone = True
            else:
                if row[4] != r_prev:
                    rd = row[pos]-r_prev
                    dt = str(t_tmp[0]+':'+t_tmp[1])
                    data.append(rd)
                    xaxis.append(dt)
                if row[4] == r_prev:
                    rd = 0.0
                    if d_tmp != d_prev:
                        dt = str(d_tmp[0][:-2]+'.'+d_tmp[1]+'.'+d_tmp[2])
                        data.append(rd)
                        xaxis.append(dt)
                    elif t_tmp[0] != t_prev[0]:
                        dt = str(t_tmp[0])
                        data.append(rd)
                        xaxis.append(dt)
            t_prev = t_tmp
            d_prev = d_tmp
            r_prev = r_tmp
        series['name'] = "Rain level"
        series['data'] = data
        divisor = len(xaxis) * 0.25
        minTick = int(len(xaxis)/divisor)
        #print len(xaxis), divisor, minTick
        if minTick == 0:
            minTick = 1
    else:
        print "No data found"
        return ''
     
    # Highcharts snippet
    c_code_1 = """
    <!DOCTYPE HTML>
    <html>
	   <head>
		  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		  <title>EventGhost Rain Report</title>
		  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
		  <style type="text/css">
    ${demo.css}
		  </style>
		  <script type="text/javascript">
    $(function () {
        $('#container').highcharts({
        chart: {
            type: 'column',
            zoomType: 'x',
            panning: true,
            panKey: 'shift'
        },
        title: {
            text: 'Rain Report using HighCharts',
            x: -20 //center
        },
        subtitle: {
            text: """
    c_code_2 = tableId
    c_code_3_1 = """,
            x: -20
        },
        xAxis: {
            minTickInterval: """
    c_code_3_2 = str(minTick)
    c_code_3_3 = """,
            categories: """
    c_code_4 = str(xaxis)
    c_code_5 = """
        },
        yAxis: {
            title: {
                text: 'Rain level (mm)'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: 'mm'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: ["""
    c_code_6 = str(series).replace("'data':", "data:")
    c_code_6 = c_code_6.replace("'name':", "name:")
    c_code_7 = """
            ]
        });
    });
    </script>
    </head>
    <body>
    <script src="js/highcharts.js"></script>
    <script src="js/modules/exporting.js"></script>
    <div id="container" style="min-width: 1000px; height: 450px; margin: 0 auto"></div>
   	</body>
    </html>
    """    
    c_code = (
        c_code_1+
        '"'+
        c_code_2+
        '"'+
        c_code_3_1+
        c_code_3_2+
        c_code_3_3+
        c_code_4+
        c_code_5+
        c_code_6+
        c_code_7
    )
    logstr += c_code
    logstr += "<h4>Selected period: "+selectedPeriod+"</h4>"
    logstr += "<h4>Total rain during period: "+periodRain+" mm</h4>"

    fName = tableId+'.html'
    fileHandle = None
    if not os.path.exists(fPath) and not os.path.isdir(fPath):
            os.makedirs(fPath)
    fileHandle = open(fPath+'/'+fName, 'a')
    fileHandle.seek(0)
    fileHandle.truncate()
    fileHandle.write(logstr.encode('utf-8'))
    fileHandle.close()


