{% extends 'base.html' %}
{% block title %}Charts{% endblock %}
{% block custom_scripts %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.6.1/socket.io.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript" src="https://unpkg.com/dygraphs@2.2.1/dist/dygraph.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/dygraphs@2.2.1/dist/extras/synchronizer.js"></script>
<link rel="stylesheet" type="text/css" href="https://unpkg.com/dygraphs@2.2.1/dist/dygraph.min.css" />

<style>
	#chart0, #chart1, #chart2, #chart3 { width: 100%; height: 60vh; }
	.dygraph-legend {
		background: var(--bs-body-bg);
	}
	.dygraph-axis-label, .dygraph-axis-label-x {
		color: var(--bs-body-color);
	}
	.w-md-100 {
	  width: 100%;
	}

	@media (min-width: 992px) { /* Bootstrap sm breakpoint */
	  .w-md-100 {
	    width: auto; /* Lub inna szerokość */
	  }
}
</style>

{% endblock %}

{% block page_body %}

<div class="row justify-content-center">
    <div class="col-12 col-lg-10 col-xl-10 mx-auto">
	
        <div class="row">
            <div class="col-lg-6 col-md-12">
                <h2 class="display-6 float-sm-start" data-i18n="charts.temp">charts.temp</h2>
            </div>
<div class="col-lg-6 col-md-12 text-end my-auto"><div class="btn-group w-md-100" role="group" aria-label="Basic radio toggle button group">

	<input type="radio" class="btn-check" value="144" name="btnradio" id="btnradio1" autocomplete="off">
  <label class="btn btn-outline-secondary" for="btnradio1" data-i18n="charts.all">All</label>

  <input type="radio" class="btn-check" value="48" name="btnradio" id="btnradio2" autocomplete="off">
  <label class="btn btn-outline-secondary" for="btnradio2" data-i18n="charts.48h">48h</label>

  <input type="radio" class="btn-check" value="12" name="btnradio" id="btnradio3" autocomplete="off" checked>
  <label class="btn btn-outline-secondary" for="btnradio3" data-i18n="charts.12h">12h</label>
  <input type="radio" class="btn-check" value="1" name="btnradio" id="btnradio4" autocomplete="off">
  <label class="btn btn-outline-secondary" for="btnradio4" data-i18n="charts.live">Live</label>
  <div class="btn-group" role="group">
    <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
      Export
    </button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item" href="#">CSV</a></li>
      <li><a class="dropdown-item" href="#">XLSX</a></li>
    </ul>
  </div>
	</div></div>
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">
                       	<div id="chart0"></div>
<div class="btn-group btn-group-sm w-100 pt-3" role="group" aria-label="Basic checkbox toggle button group">
  <input type="checkbox" checked class="btn-check" name="0" data-chart="0" id="vistank" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vistank">tank</label>
  <input type="checkbox" checked class="btn-check" name="1" data-chart="0" id="vistwi" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vistwi">twi</label>
  <input type="checkbox" checked class="btn-check" name="2" data-chart="0" id="vistwo" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vistwo">two</label>
  <input type="checkbox" checked class="btn-check" name="3" data-chart="0" id="visthi" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visthi">thi</label>
  <input type="checkbox" checked class="btn-check" name="4" data-chart="0" id="vistho" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vistho">tho</label>
  <input type="checkbox" checked class="btn-check" name="5" data-chart="0" id="vists" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vists">ts</label>
  <input type="checkbox" checked class="btn-check" name="6" data-chart="0" id="vistd" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vistd">td</label>
  <input type="checkbox" checked class="btn-check" name="7" data-chart="0" id="vistao" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vistao">tao</label>
  <input type="checkbox" checked class="btn-check" name="8" data-chart="0" id="visintemp" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visintemp">intemp</label>
  <input type="checkbox" checked class="btn-check" name="9" data-chart="0" id="vishumid" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vishumid">humid</label>
  <input type="checkbox" checked class="btn-check" name="10" data-chart="0" id="visouttemp" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visouttemp">outtemp</label>
  <input type="checkbox" checked class="btn-check" name="11" data-chart="0" id="vishcurve" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vishcurve">hcurve</label>
</div>

                    </div>
                </div>
            </div>
        </div>


        <div class="row">
            <div class="col-lg-6">
                <h2 class="display-6 float-sm-start" data-i18n="charts.freq">charts.freq</h2>
            </div>
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">
			    <div id="chart1"></div>
<div class="btn-group btn-group-sm w-100 pt-3" role="group" aria-label="Basic checkbox toggle button group">
  <input type="checkbox" checked class="btn-check" name="0" data-chart="1" id="visfset" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visfset">fset</label>
  <input type="checkbox" checked class="btn-check" name="1" data-chart="1" id="visfact" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visfact">fact</label>
  <input type="checkbox" checked class="btn-check" name="2" data-chart="1" id="visflimit" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visflimit">flimit</label>
</div>
                    </div>
                </div>
            </div>
        </div>


        <div class="row">
            <div class="col-lg-6">
                <h2 class="display-6 float-sm-start" data-i18n="charts.modes">charts.modes</h2>
            </div>
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">
                        <div id="chart2"></div>
<div class="btn-group btn-group-sm w-100 pt-3" role="group" aria-label="Basic checkbox toggle button group">
  <input type="checkbox" checked class="btn-check" name="0" data-chart="2" id="visquiet" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visquiet">Quiet</label>
  <input type="checkbox" checked class="btn-check" name="1" data-chart="2" id="viseco" autocomplete="off">
  <label class="btn btn-outline-secondary" for="viseco">Eco</label>
  <input type="checkbox" checked class="btn-check" name="2" data-chart="2" id="visturbo" autocomplete="off">
  <label class="btn btn-outline-secondary" for="visturbo">Turbo</label>
</div>

                    </div>
                </div>
            </div>
        </div>
		
        <div class="row">
            <div class="col-lg-6">
                <h2 class="display-6 float-sm-start" data-i18n="charts.presure">charts.presure</h2>
            </div>
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">
			    <div id="chart3"></div>
<div class="btn-group btn-group-sm w-100 pt-3" role="group" aria-label="Basic checkbox toggle button group">
  <input type="checkbox" checked class="btn-check" name="0" data-chart="3" id="vispsset" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vispsset">Ps set</label>
  <input type="checkbox" checked class="btn-check" name="1" data-chart="3" id="vispsact" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vispsact">Ps act</label>
  <input type="checkbox" checked class="btn-check" name="2" data-chart="3" id="vispdset" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vispdset">Pd set</label>
  <input type="checkbox" checked class="btn-check" name="3" data-chart="3" id="vispdact" autocomplete="off">
  <label class="btn btn-outline-secondary" for="vispdact">Pd act</label>
</div>

                    </div>
                </div>
            </div>
        </div>
		
		
    </div>
</div>
    <script>
$(document).ready(function() {
$('input').click( function() {
    charts[$(this).data('chart')].chart.setVisibility($(this)[0].name, $(this)[0].checked)
    console.log($(this)[0].name)
    console.log($(this)[0].id)
    console.log($(this).data('chart'))
})
chartsConfig = {
    chart0: {
        labels: ["Date", "tank", "twi", "two", "thi", "tho", "ts", "td", "tao", "intemp", "humid", "outtemp", "hcurve"],
        colors: ["#FF0000", "#00367F","#4BC0C0","#9966FF","#FF9F40","#FF5733","#EBC7D8","#008000","#ADD8E6","#D7D741","#FF00FF","#994C00"],
	visibility: [true,true,true,true,true,true,true,true,true,true,true,true],
        data: [[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]]
    },
    chart1: {
	labels: ["Date", "F set", "F act", "F limit"],
	colors: ["#C9CBCF", "#00367F", "#FFBF00"],
	visibility: [true,true,true],
	data: []
	},
    chart2:{
	labels: ["Date", "Quiet", "Eco", "Turbo"],
	colors: ["#90EE90", "#FF5F00", "#CC0000"],
	visibility: [true,true,true],
	data: []
	},
    chart3:{
	labels: ["Date", "Ps set", "Ps act", "Pd set", "Pd act"],
	colors: ["#4BC0C0", "#00367F", "#FF00FF", "#9966FF"],
	visibility: [true,true,true,true],
	data: []
	}
	    };
    socket = io(); // Upewniamy się, że socket jest tworzony tylko raz

    socket.on("connect", () => {
        console.log("Połączono z serwerem Socket.io");
    });
        socket.on('charts', function(data) {
			    console.log(data)
const chartdate = data['chartdate']
const charttank = data['charttank']
const charttwi = data['charttwi']
const charttwo = data['charttwo']
const chartthi = data['chartthi']
const charttho = data['charttho']
const chartts = data['chartts']
const charttd = data['charttd']
const charttao = data['charttao']
const chartintemp = data['chartintemp']
const charthumid = data['charthumid']
const chartouttemp = data['chartouttemp']
const charthcurve = data['charthcurve']
const chartfset = data['chartfset']
const chartfact = data['chartfact']
const chartflimiton = data['chartflimiton']
const chartmode_quiet = data['chartmode_quiet']
const chartmode_eco = data['chartmode_eco']
const chartmode_turbo = data['chartmode_turbo']
const chartpsset = data['chartpsset']
const chartpsact = data['chartpsact']
const chartpdset = data['chartpdset']
const chartpdact = data['chartpdact']
	
chartsConfig.chart0.data = formatChartData({
		chartdate,
        charttank,
        charttwi,
        charttwo,
        chartthi,
        charttho,
        chartts,
        charttd,
        charttao,
        chartintemp,
        charthumid,
        chartouttemp,
        charthcurve
        });
chartsConfig.chart1.data = formatChartData({
		chartdate,
		chartfset,
		chartfact,
	        chartflimiton
		    });
chartsConfig.chart2.data = formatChartData({
		chartdate,
		chartmode_quiet,
        	chartmode_eco,
        	chartmode_turbo
		    });
chartsConfig.chart3.data = formatChartData({
		chartdate,
		chartpsset,
        	chartpsact,
        	chartpdset,
        	chartpdact
	});

generateOrUpdateDygraph("chart0", chartsConfig.chart0);
generateOrUpdateDygraph("chart1", chartsConfig.chart1);
generateOrUpdateDygraph("chart2", chartsConfig.chart2);
generateOrUpdateDygraph("chart3", chartsConfig.chart3);

Dygraph.synchronize(charts.map(c => c.chart), {
  zoom: true,
  selection: true,
  range: false
});

});
        socket.on('chart_update', function(msg) {
			    if ($('#btnradio4').prop('checked')) {
						console.log("UPDATE")
		chartsConfig.chart0.data.push([new Date(msg.datechart), msg.tankchart, msg.twichart, msg.twochart, msg.thichart, msg.thochart, msg.tschart, msg.tdchart, msg.taochart, isNaN(msg.intempchart) || msg.intempchart === "ERROR" || msg.intempchart === "" ? null : parseFloat(msg.intempchart), isNaN(msg.humidchart) || msg.humidchart === "ERROR" || msg.humidchart === "" ? null : parseFloat(msg.humidchart), msg.outtempchart, msg.hcurvechart])
                chartsConfig.chart1.data.push([new Date(msg.datechart), msg.fsetchart, msg.factchart, isNaN(msg.flimitonchart) || msg.flimitonchart === "ERROR" || msg.flimitonchart === "" ? null : parseFloat(msg.flimitonchart),])
                chartsConfig.chart2.data.push([new Date(msg.datechart), msg.modechart_quiet, msg.modechart_eco, msg.modechart_turbo])
                chartsConfig.chart3.data.push([new Date(msg.datechart), msg.pssetchart, msg.psactchart, msg.pdsetchart, msg.pdactchart])

			    generateOrUpdateDygraph("chart0", chartsConfig.chart0);
generateOrUpdateDygraph("chart1", chartsConfig.chart1);
generateOrUpdateDygraph("chart2", chartsConfig.chart2);
generateOrUpdateDygraph("chart3", chartsConfig.chart3);
					} else {
							    console.log("NIE UPDATE")
						    }

        });
});
charts = [];
function formatChartData(rawData) {
    const { chartdate, ...series } = rawData; // Oddzielenie dat od serii danych

    return chartdate.map((date, index) => [
        new Date(date), // Konwersja daty na obiekt Date
        ...Object.values(series).map(arr => {
            const value = arr[index];
            return isNaN(value) || value === "ERROR" || value === "" ? null : parseFloat(value);
        })
    ]);
}

function generateOrUpdateDygraph(divId, config) {
		    // Jeśli wykres o danym divId już istnieje, aktualizujemy go
    let existingChart = charts.find(chartObj => chartObj.divId === divId);
    if (existingChart) {
        // Aktualizacja danych; .slice() tworzy nową referencję
        existingChart.chart.updateOptions({ 'file': config.data.slice(), dateWindow: null });
    } else {
        // Inicjalizacja nowego wykresu
        const chart = new Dygraph(
            document.getElementById(divId),
            config.data,
            {
		legend: 'follow',
		visibility: config.visibility,
                labels: config.labels,
                ylabel: "Wartość",
                xlabel: "Czas",
                showRoller: true,
		connectSeparatedPoints: true,
                colors: config.colors
            }
        );
        // Zachowujemy identyfikator kontenera, by móc później odnaleźć wykres
        charts.push({ divId, chart });
    }
}

	    $("input[name='btnradio']").click( function () { socket.emit('client', {charts: $(this).val()}) });


    </script>
{% endblock %}

