//defaults
var default_granularity = '5m'; // needs to be specified as string, changes
var default_hours = 24;         // int is OK, (h) hardcoded
var default_end = 0;            // detto
var base_url = "https://bastart.spoton.cz/data/";
var counter = 0;
var tout = 5000;                // fresh date refresh rate, in ms
var g_tout = 30000;             // graph update rate, in ms

//initialize the uninitialized
var hours = new Object();
var granularity = new Object();
var end = new Object();
var graphdata = new Object();
var data = new Object();

// types match function names in python's Dynamic.py class
var types = Array('wind_monitor',
    'temphumi_monitor',
    'pressure_monitor',
    'rrate_monitor');

// Now let's set up the defaults and primary data sources, leter changed dynamically
var types_size = types.length;
for(var i=0; i<types_size; i++){
    var type = types[i];
    hours[type] = default_hours;
    granularity[type] = default_granularity;
    end[type] = default_end;
    if(type == 'wind_monitor'){
        hours[type] = 12;
        granularity[type] = '1m';
    }
    data[type] = base_url + type + "?range=" + hours[type] + "h&granularity=" + granularity[type] + "&end=" + default_end + "h";
    if(type == 'pressure_monitor'){
        hours[type] = 168;
        granularity[type] = '1h';
        data[type] = base_url + type + "?range=" + hours[type] + "h&granularity=" + granularity[type] + "&end=" + default_end + "h";
    }
    if(type == 'rrate_monitor'){
        hours[type] = 168;
        granularity[type] = '1h';
        data[type] = base_url + type + "?range=" + hours[type] + "h&granularity=" + granularity[type] + "&end=" + default_end + "h";
    }
}

wind = new Dygraph(
document.getElementById("wind"),
data['wind_monitor'],
{
    axes : {
            x : {
                drawGrid: true,
                drawAxis : true
            },
            y : {
                drawGrid: false,
                drawAxis : true,
            },
            y2 : {
                drawGrid: false,
                drawAxis: true,
                valueRange: [0,360],
                independentTicks: true
            }
    },
    rollPeriod: 5,
    interactionModel: {},
    connectSeparatedPoints: true,
    series:{
        'Speed': {
            axis: 'y',
            color: '#444444',
            fillGraph: true,
            fillAlpha: 0.4
        },
        'Gusts': {
            axis: 'y',
            color: '#ff5555'
        },
        'Direction': {
            axis: 'y2',
            color: '#999999'
        }
    },
        ylabel: '<span style="color:#444444;">Speed<span style="color:#444444;"> / <span style="color:#ff5555;">Gusts</span> [km/h]',
        y2label: '<span style="color:#999999;">Direction [&deg;]</span>',
        labelsDiv: 'wind_labels',
        legend: 'always'
    }
);

temphumi_out = new Dygraph(
document.getElementById("temphumi"),
data['temphumi_monitor'],
{
    axes : {
            x : {
                drawGrid: true,
                drawAxis : false
            },
            y : {
                drawGrid: false,
                drawAxis : true,
            },
            y2 : {
                drawGrid: false,
                drawAxis: true,
                independentTicks: true
            }
    },
    rollPeriod: 5,
    visibility: [false, true, false, true],
    interactionModel: {},
    connectSeparatedPoints: true,
    series:{
        'T(out)': {
            axis: 'y',
            color: '#705555',
            fillGraph: true,
            fillAlpha: 0.2
        },
        'T(ins)': {
            axis: 'y',
            color: '#705555',
            fillGraph: true,
            fillAlpha: 0.2
        },
        'Humi(out)': {
            axis: 'y2',
            color: '#222288'
        },
        'Humi(ins)': {
            axis: 'y2',
            color: '#222288'
        }
    },
        ylabel: '<span style="color:#555555;">Outside [&deg;C]</span>',
        y2label: '<span style="color:#222288;">Humidity [%]</span>',
        labelsDiv: 'temphumi_labels',
        legend: 'always'
    }
);

temphumi_in = new Dygraph(
document.getElementById("temphumi_in"),
data['temphumi_monitor'],
{
    axes : {
            x : {
                drawGrid: true,
                drawAxis : true
            },
            y : {
                drawGrid: false,
                drawAxis : true,
                valueRange: [10,35]
            },
            y2 : {
                drawGrid: false,
                drawAxis: true,
                independentTicks: true,
                valueRange: [0,100]
            }
    },
    rollPeriod: 5,
    visibility: [true, false, true, false],
    interactionModel: {},
    connectSeparatedPoints: true,
    series:{
        'T(out)': {
            axis: 'y',
            color: '#705555',
            fillGraph: true,
            fillAlpha: 0.2
        },
        'T(ins)': {
            axis: 'y',
            color: '#705555',
            fillGraph: true,
            fillAlpha: 0.2
        },
        'Humi(out)': {
            axis: 'y2',
            color: '#222288'
        },
        'Humi(ins)': {
            axis: 'y2',
            color: '#222288'
        }
    },
        ylabel: '<span style="color:#555555;">Inside [&deg;C]</span>',
        y2label: '<span style="color:#222288;">Humidity [%]</span>',
        labelsDiv: 'temphumi_labels_in',
        legend: 'always'
    }
);

pressure = new Dygraph(
document.getElementById("pressure"),
data['pressure_monitor'],
{
    axes : {
            x : {
                drawGrid: true,
                drawAxis : true
            },
            y : {
                drawGrid: false,
                drawAxis : true,
                valueRange: [970,1055]
            },
            y2 : {
                drawGrid: false,
                drawAxis: true,
                valueRange: [970,1055]
            }
    },
    rollPeriod: 20,
    interactionModel: {},
    connectSeparatedPoints: true,
    visibility: [true, false],
    series:{
        'Pressure': {
            axis: 'y',
            color: '#557070',
            fillGraph: true,
            fillAlpha: 0.5
        },
        'Pressure': {
            axis: 'y2',
            color: '#557070',
            fillGraph: true,
            fillAlpha: 0.5
        }
    },
        ylabel: '<span style="color:#555555;">Pressure [hPa]</span>',
        labelsDiv: 'pressure_labels',
        legend: 'always'
    }
);

rrate = new Dygraph(
document.getElementById("rrate"),
data['rrate_monitor'],
{
    axes : {
            x : {
                drawGrid: true,
                drawAxis : true
            },
            y : {
                drawGrid: false,
                drawAxis : true,
                valueRange: [0,3]
            },
            y2 : {
                drawGrid: false,
                drawAxis: true,
                valueRange: [0,3]
            }
    },
    rollPeriod: 0,
    interactionModel: {},
    connectSeparatedPoints: true,
    visibility: [true, true],
    series:{
        'Rrate': {
            axis: 'y',
            color: '#0055ff',
            fillGraph: true,
            fillAlpha: 0.5
        },
        'Rrate_max': {
            axis: 'y2',
            color: '#0000aa',
            fillGraph: false
        }
    },
        ylabel: '<span style="color:#555555;">Rain rate [mm/h]</span>',
        labelsDiv: 'rrate_labels',
        legend: 'always'
    }
);

// Functions for buttons to scale / move graphs
function refreshGraph(source){
  graphdata[source] = "https://bastart.spoton.cz/data/" + source + "?range=" + hours[source] + "h&granularity=" + granularity[source] + "&end=" + end[source] + "h";
  if(source == 'wind_monitor'){
      wind.updateOptions({'file': graphdata[source]});
  }
  if(source == 'temphumi_monitor'){
      temphumi_out.updateOptions({'file': graphdata[source]});
      temphumi_in.updateOptions({'file': graphdata[source]});
  }
  if(source == 'pressure_monitor'){
      pressure.updateOptions({'file': graphdata[source]});
  }
  if(source == 'rrate_monitor'){
      rrate.updateOptions({'file': graphdata[source]});
  }
  // TODO: adjust to update graph timestamps per click on ranges
  // document.getElementById('g_tstamp_' + source).innerHTML = freshVals.time;
}

// here, target needs to match the python's dynamic class again
function setHours(hours_to_set, target){
  hours[target] = hours_to_set;
  switch(hours[target]){
      case '1':
        granularity[target] = '30s';
        if(target == 'temphumi_monitor'){ granularity[target] = '2m';}
        break;
      case '6':
        granularity[target] = '1m';
        if(target == 'temphumi_monitor'){ granularity[target] = '2m';}
        break;
      case '12':
        granularity[target] = '2m';
        if(target == 'temphumi_monitor'){ granularity[target] = '2m';}
        break;
      case '24':
        granularity[target] = '5m';
        if(target == 'temphumi_monitor'){ granularity[target] = '2m';}
        break;
      case '168':
        granularity[target] = '10m';
        break;
      case '720':
        granularity[target] = '1h';
        break;
      case '4320':
        granularity[target] = '12h';
        break;
      case '8640':
        granularity[target] = '24h';
        break;
      default:
        granularity[target] = default_granularity;
  }
  end[target] = 0;
  refreshGraph(target);
}

// Functions for buttons to scale / move graphs
function setBack(target){
    disp_range = hours[target]*1 - end[target]*1;
    hours[target] = hours[target]*1 + disp_range;
    end[target] = end[target]*1 + disp_range;
    refreshGraph(target);
}

function setForth(target){
    disp_range = hours[target]*1 - end[target]*1;
    hours[target] = hours[target]*1 - disp_range;
    if(hours[target] < disp_range){
        hours[target] = disp_range;
    }
    end[target] = end[target]*1 - disp_range;
    if(end[target] < 0){
        end[target] = 0;
    }
    refreshGraph(target);
}

function getPageContents(callback,url,params) {
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari, SeaMonkey
        xmlhttp=new XMLHttpRequest();
    }
    else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(params!=null) {
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    } else {
        xmlhttp.open("GET", url, true);
    }
    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.send(params);
}

function refreshValues(){
    fresh_vals_url = '/data/weather_realtime_data?type=json'
    getPageContents(function(result){freshVals=JSON.parse(result);},
                     fresh_vals_url)
    document.getElementById('timestamp').innerHTML = freshVals.time;                 
    document.getElementById('w_speed_km').innerHTML = freshVals.wind.speed;
    document.getElementById('w_speed_ms').innerHTML = freshVals.wind.speed_ms;
    document.getElementById('w_dir').innerHTML = freshVals.wind.dir;
    document.getElementById('w_gust_km').innerHTML = freshVals.wind.gust;
    document.getElementById('w_gust_ms').innerHTML = freshVals.wind.gust_ms;
    document.getElementById('w_dir_name').innerHTML = freshVals.wind.dir_name;
    document.getElementById('out_temp').innerHTML = freshVals.temperature.out;
    document.getElementById('in_temp').innerHTML = freshVals.temperature.in;
    document.getElementById('current_pressure').innerHTML = freshVals.pressure;
    document.getElementById('current_rrate').innerHTML = freshVals.rainrate;
    counter = counter + tout;
    if(counter >= g_tout){
        for(var i=0; i<types_size; i++){
            var type = types[i];
            refreshGraph(type);
            document.getElementById('g_tstamp_' + type).innerHTML = freshVals.time;
        }
        counter = 0;
    }
}
var intervalVal = setInterval(refreshValues, tout);
