/*
 * Copyright 2021 - All rights reserved.
 * Rodrigo Tapia-McClung
 *
 * March 2021
 */

/* globals am4core, am4charts, am4themes_animated, baseUrl */

let mainTextColor = getComputedStyle(document.body).getPropertyValue("--main-text-color");
//let cellbgColor = getComputedStyle(document.body).getPropertyValue("--main-bg-color");

const makeStackedBarSeries = (chart, name, category, value, color, units="Ha") => {
    let series = chart.series.push(new am4charts.ColumnSeries());
    series.columns.template.width = am4core.percent(80);
    series.name = name;
    series.units = units;
    series.dataFields.categoryX = category;
    series.dataFields.valueY = value;
    series.columns.template.tooltipText ="{name}: {valueY.formatNumber('#,###.00')} {units}";
    series.dataItems.template.locations.categoryX = 0.5;
    series.stacked = true;
    series.tooltip.pointerOrientation = "vertical";
    series.fill = am4core.color(color);
    series.stroke = am4core.color(color);
}

const makeLineSeries = (chart, name, value, percent, category, yAxis, color) => {
    let series = chart.series.push(new am4charts.LineSeries());
    series.name = name;//"San Juan del río - Querétaro";
    series.dataFields.valueY = value;
    series.dataFields.categoryX = category;
    if (percent) {
        series.dataFields.valueYShow = "totalPercent";
        series.stacked = true;
        series.calculatePercent = true;
    }
    // FIXME: using totalPercent chanhges values when turning series on or off
    series.yAxis = yAxis;
    series.stroke = am4core.color(color);
    series.strokeWidth = 3;
    series.propertyFields.strokeDasharray = "lineDash";
    series.tooltip.label.textAlign = "middle";

    let bullet = series.bullets.push(new am4charts.Bullet());
    bullet.fill = am4core.color(color); // tooltips grab fill from parent by default
    bullet.tooltipText = "[#fff font-size: 15px]{name} en {categoryX}:\n[/][#fff font-size: 15px]{valueY.totalPercent.formatNumber('#.00')} %[/] [#fff][/]";
    // FIXME: using totalPercent chanhges values when turning series on or off`

    let circle = bullet.createChild(am4core.Circle);
    circle.radius = 4;
    circle.fill = am4core.color("#fff");
    circle.strokeWidth = 3;
}

am4core.ready(function() {

    // Themes begin
    am4core.useTheme(am4themes_animated);
    // Themes end

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++BARRAS SEMAFORO++
    /*
    FALTA VER DE QUÉ TABLA VIENEN ESTOS DATOS Y ELEGIR LA VERSION EN PIXELES
    Y CONSTRUIR EL QUERY
    */

    let stackedBarChart = am4core.create("topLeftChart", am4charts.XYChart);
    stackedBarChart.hiddenState.properties.opacity = 0; // this creates initial fade-in

    /*
  let table = "periurbanoBajio";
  let query = `${baseUrl}/query/${table}?columns=region,total15/1000 as T15,total16/1000 as T16,total17/1000 as T17,total18/1000 as T18,total19/1000 as T19,total20/1000 as T20,&filter=id=6`;
  d3.json(query).then(d => chart.data = d);
*/
    let stackedBarTitle = stackedBarChart.titles.create();
    stackedBarTitle.text = "Grado de urbanización en la RU-CMCP (millares de pixeles)";
    stackedBarTitle.fontSize = 15;
    stackedBarTitle.marginBottom = 10;
    stackedBarTitle.fill = am4core.color(mainTextColor);

    stackedBarChart.data = [
        {
            category: "2015",
            value1: 954,
            value2: 145,
            value3: 76
        },
        {
            category: "2016",
            value1: 1084,
            value2: 167,
            value3: 94
        },
        {
            category: "2017",
            value1: 1195,
            value2: 191,
            value3: 115
        },
        {
            category: "2018",
            value1: 1304,
            value2: 216,
            value3: 140
        },
        {
            category: "2019",
            value1: 1373,
            value2: 230,
            value3: 156
        },
        {
            category: "2020",
            value1: 1418,
            value2: 242,
            value3: 170
        }
    ];
    stackedBarChart.legend = new am4charts.Legend();
    stackedBarChart.legend.fontSize = 15;
    stackedBarChart.legend.labels.template.fill = am4core.color(mainTextColor);

    let stackedBarCategoryAxis = stackedBarChart.xAxes.push(new am4charts.CategoryAxis());
    stackedBarCategoryAxis.dataFields.category = "category";
    stackedBarCategoryAxis.renderer.grid.template.location = 0;
    stackedBarCategoryAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    stackedBarCategoryAxis.renderer.labels.template.fontSize = 15;

    let stackedBarValueAxis = stackedBarChart.yAxes.push(new am4charts.ValueAxis());
    stackedBarValueAxis.min = 0;
    //valueAxis.max = 100;
    stackedBarValueAxis.strictMinMax = true;
    stackedBarValueAxis.calculateTotals = true;
    stackedBarValueAxis.renderer.minWidth = 50;
    stackedBarValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    stackedBarValueAxis.renderer.labels.template.fontSize = 15;

    makeStackedBarSeries(stackedBarChart, "Bajo", "category", "value1", "#61ac65", "Millares de pixeles");
    makeStackedBarSeries(stackedBarChart, "Medio", "category", "value2", "#fcfccc", "Millares de pixeles");
    makeStackedBarSeries(stackedBarChart, "Alto", "category", "value3", "#b33d6e", "Millares de pixeles");

    //++++++++++++++++++++++++++++++++++++++++++++ BARRAS CAFES Y LINEAS MORADAS APILADAS ++++++++++++++++++
    // FALTA CONSTRUIR QUERY

    let stackedBarLineChart = am4core.create("topRightChart", am4charts.XYChart);
    stackedBarLineChart.hiddenState.properties.opacity = 0; // this creates initial fade-in

    /*
  let table = "periurbanoBajio";
  let query = `${baseUrl}/query/${table}?columns=region,grbajo15/1000 as b15,grmedio15/1000 as b16,gralto15/1000 as a15 .... &filter=id=6`;
  d3.json(query).then(d => chart.data = d);
*/
    let stackedBarLineTitle = stackedBarLineChart.titles.create();
    stackedBarLineTitle.text = "Evolución del grado de urbanización en el periurbano del \n Corredor del Bajío en extensión y proporción";
    stackedBarLineTitle.fontSize = 15;
    stackedBarLineTitle.marginBottom = 10;
    stackedBarLineTitle.fill = am4core.color(mainTextColor);

    stackedBarLineChart.data = [
        {
            category: "2015",
            value1: 21750.100923,
            value2: 3124.799027,
            value3: 1575.434647
        },
        {
            category: "2016",
            value1: 24659.53423,
            value2: 3621.838793,
            value3: 1939.124265
        },
        {
            category: "2017",
            value1: 27560.13116,
            value2: 4177.560407,
            value3: 2393.056475
        },
        {
            category: "2018",
            value1: 30374.679993,
            value2: 4719.515675,
            value3: 2854.437993
        },
        {
            category: "2019",
            value1: 32656.93783,
            value2: 5188.035213,
            value3: 3357.159708
        },
        {
            category: "2020",
            value1: 34305.410194,
            value2: 5602.741586,
            value3: 3789.051441
        }
    ];

    stackedBarLineChart.legend = new am4charts.Legend();
    stackedBarLineChart.legend.fontSize = 15;
    stackedBarLineChart.legend.labels.template.fill = am4core.color(mainTextColor);

    let stackedBarLineCategoryAxis = stackedBarLineChart.xAxes.push(new am4charts.CategoryAxis());
    stackedBarLineCategoryAxis.dataFields.category = "category";
    stackedBarLineCategoryAxis.renderer.grid.template.location = 0;
    stackedBarLineCategoryAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    stackedBarLineCategoryAxis.renderer.labels.template.fontSize = 15;

    let stackedBarLineValueAxis = stackedBarLineChart.yAxes.push(new am4charts.ValueAxis());
    stackedBarLineValueAxis.min = 0;
    //stackedBarLineValueAxis.max = 100;
    stackedBarLineValueAxis.strictMinMax = true;
    stackedBarLineValueAxis.calculateTotals = true;
    stackedBarLineValueAxis.renderer.minWidth = 50;
    stackedBarLineValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    stackedBarLineValueAxis.renderer.labels.template.fontSize = 15;

    /* Create secondary value axis */
    let stackedBarLinePercentAxis = stackedBarLineChart.yAxes.push(new am4charts.ValueAxis());
    stackedBarLinePercentAxis.renderer.opposite = true;
    stackedBarLinePercentAxis.calculateTotals = true;
    stackedBarLinePercentAxis.min = 50;
    stackedBarLinePercentAxis.max = 110;
    stackedBarLinePercentAxis.strictMinMax = true;
    stackedBarLinePercentAxis.renderer.grid.template.disabled = true;
    stackedBarLinePercentAxis.numberFormatter = new am4core.NumberFormatter();
    stackedBarLinePercentAxis.numberFormatter.numberFormat = "#'%'";
    stackedBarLinePercentAxis.cursorTooltipEnabled = false;
    stackedBarLinePercentAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    stackedBarLinePercentAxis.renderer.labels.template.fontSize = 15;

    makeStackedBarSeries(stackedBarLineChart, "Bajo", "category", "value1", "#f8caa0");
    makeStackedBarSeries(stackedBarLineChart, "Medio", "category", "value2", "#cf8a4f");
    makeStackedBarSeries(stackedBarLineChart, "Alto", "category", "value3", "#93592a");

    makeLineSeries(stackedBarLineChart, "% Bajo", "value1", true, "category", stackedBarLinePercentAxis, "#D197FA");
    makeLineSeries(stackedBarLineChart, "% Medio", "value2", true, "category", stackedBarLinePercentAxis, "#844DDF");
    makeLineSeries(stackedBarLineChart, "% Alto", "value3", true, "category", stackedBarLinePercentAxis, "#351591");

    // Use this to avoid turning on or off legend items.
    // Remove if use of percentTotal is fixed in series
    stackedBarLineChart.legend.itemContainers.template.clickable = false;
    stackedBarLineChart.legend.itemContainers.template.focusable = false;
    stackedBarLineChart.legend.itemContainers.template.cursorOverStyle = am4core.MouseCursorStyle.default;
    stackedBarLineChart.legend.maxColumns = 3;

    //++++++++++++++++++++++++++++++++++++++++++++ HISTORICO POR TRAMOS ++++++++++++++++++

    let lineChart = am4core.create("bottomLeftChart", am4charts.XYChart);
    lineChart.hiddenState.properties.opacity = 0; // this creates initial fade-in

    /*
  let table = "periurbanoBajio";
  let query = `${baseUrl}/query/${table}?columns=region,total15/1000 as T15,total16/1000 as T16,total17/1000 as T17,total18/1000 as T18,total19/1000 as T19,total20/1000 as T20,&filter=id>6&id<13&sort=inc desc`;
  d3.json(query).then(d => chart.data = d);
*/

    let lineTitle = lineChart.titles.create();
    lineTitle.text = "Crecimiento del medio construido en 6 tramos del Corredor del Bajío";
    lineTitle.fontSize = 14;
    lineTitle.marginBottom = 15;
    lineTitle.fill = am4core.color(mainTextColor);

    lineChart.data = [
        {
            category: "2015",
            Tramo7: 35.65151797,
            Tramo8: 44.02997137,
            Tramo9: 29.82665968,
            Tramo10: 15.71134834,
            Tramo11: 39.09316004,
            Tramo12: 6.57480063
        },
        {
            category: "2016",
            Tramo7: 39.29417937,
            Tramo8: 47.79702192,
            Tramo9: 34.77272593,
            Tramo10: 18.80688948,
            Tramo11: 46.87034719,
            Tramo12: 8.08189062
        },
        {
            category: "2017",
            Tramo7: 43.44194901,
            Tramo8: 52.9003468,
            Tramo9: 41.84257241,
            Tramo10:21.68042568,
            Tramo11:53.54295853,
            Tramo12:9.46076199
        },
        {
            category: "2018",
            Tramo7: 47.12061739,
            Tramo8: 57.98574005,
            Tramo9: 49.04355871,
            Tramo10: 24.63225593,
            Tramo11: 60.65936419,
            Tramo12: 10.77998678
        },
        {
            category: "2019",
            Tramo7:  50.04426599,
            Tramo8:  61.12824022,
            Tramo9:  53.97632509,
            Tramo10: 27.75836758,
            Tramo11: 67.83400364,
            Tramo12: 12.38459944
        },
        {
            category: "2020",
            Tramo7:  53.6443353,
            Tramo8:  64.27625949,
            Tramo9:  57.22221469,
            Tramo10: 29.72499167,
            Tramo11: 72.99502497,
            Tramo12: 13.38796796
        }

    ];

    lineChart.legend = new am4charts.Legend();
    lineChart.legend.fontSize = 15;
    lineChart.legend.labels.template.fill = am4core.color(mainTextColor);

    let lineChartCategoryAxis = lineChart.xAxes.push(new am4charts.CategoryAxis());
    lineChartCategoryAxis.dataFields.category = "category";
    lineChartCategoryAxis.renderer.grid.template.location = 0;
    lineChartCategoryAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    lineChartCategoryAxis.renderer.labels.template.fontSize = 15;

    let lineChartValueAxis = lineChart.yAxes.push(new am4charts.ValueAxis());
    lineChartValueAxis.min = 0;
    //lineChartValueAxis.max = 100;
    //lineChartValueAxis.strictMinMax = true;
    lineChartValueAxis.calculateTotals = true;
    lineChartValueAxis.renderer.minWidth = 50;
    lineChartValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    lineChartValueAxis.renderer.labels.template.fontSize = 15;

    makeLineSeries(lineChart, "T7", "Tramo7", false, "category", lineChartValueAxis, "#fddfb9");
    makeLineSeries(lineChart, "T8", "Tramo8", false, "category", lineChartValueAxis, "#fb9a99");
    makeLineSeries(lineChart, "T9", "Tramo9", false, "category", lineChartValueAxis, "#33a09b");
    makeLineSeries(lineChart, "T10", "Tramo10", false, "category", lineChartValueAxis, "#de6eb4");
    makeLineSeries(lineChart, "T11", "Tramo11", false, "category", lineChartValueAxis, "#4db0ec");
    makeLineSeries(lineChart, "T12", "Tramo12", false, "category", lineChartValueAxis, "#2be829");

    // Use this to avoid turning on or off legend items.
    // Remove if use of percentTotal is fixed in series
    lineChart.legend.itemContainers.template.clickable = false;
    lineChart.legend.itemContainers.template.focusable = false;
    lineChart.legend.itemContainers.template.cursorOverStyle = am4core.MouseCursorStyle.default;
    lineChart.legend.maxColumns = 3;


    // Create bar + percentage chart
    let barPercentChart = am4core.create("bottomRightChart", am4charts.XYChart);

    let barPercentChartTitle = barPercentChart.titles.create();
    barPercentChartTitle.text = "Cobertura del medio construido en los tramos del Corredor del Bajío";
    barPercentChartTitle.fontSize = 14;
    barPercentChartTitle.marginBottom = 15;
    barPercentChartTitle.fill = am4core.color(mainTextColor);

    let table = "periurbanoBajio";
    let query = `${baseUrl}/query/${table}?columns=substring(region,7) as region,total20/1000 as has,(total20-total15)*100/total15 as inc&filter=id>6&id<13&sort=inc desc`;
    d3.json(query).then(d => barPercentChart.data = d);

    /* Create axes */
    let barPercentCategoryAxis = barPercentChart.xAxes.push(new am4charts.CategoryAxis());
    barPercentCategoryAxis.dataFields.category = "region";
    // FIXME: axis labels are too big
    let label = barPercentCategoryAxis.renderer.labels.template;
    label.wrap = true;
    label.maxWidth = 80;
    barPercentCategoryAxis.renderer.labels.template.horizontalCenter = "right";
    barPercentCategoryAxis.renderer.labels.template.verticalCenter = "middle";
    barPercentCategoryAxis.renderer.labels.template.rotation = 270;
    barPercentCategoryAxis.renderer.minGridDistance = 30;
    barPercentCategoryAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    barPercentCategoryAxis.renderer.labels.template.fontSize = 11.5;//15;

    /* Create primary value axis */
    let barPercentValueAxis = barPercentChart.yAxes.push(new am4charts.ValueAxis());
    barPercentValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    barPercentValueAxis.renderer.labels.template.fontSize = 15;

    /* Create secondary value axis */
    let barPercentAxis = barPercentChart.yAxes.push(new am4charts.ValueAxis());
    barPercentAxis.renderer.opposite = true;
    barPercentAxis.min = 0;
    barPercentAxis.max = 110;
    barPercentAxis.strictMinMax = true;
    barPercentAxis.renderer.grid.template.disabled = true;
    barPercentAxis.numberFormatter = new am4core.NumberFormatter();
    barPercentAxis.numberFormatter.numberFormat = "#'%'";
    barPercentAxis.cursorTooltipEnabled = false;
    barPercentAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    barPercentAxis.renderer.labels.template.fontSize = 15;

    /* Create series */
    let barPercentColumnSeries = barPercentChart.series.push(new am4charts.ColumnSeries());
    barPercentColumnSeries.name = "Medio construido en 2020";
    barPercentColumnSeries.dataFields.valueY = "has";
    barPercentColumnSeries.dataFields.categoryX = "region";

    barPercentColumnSeries.columns.template.tooltipText = "[#fff font-size: 15px]{name} \n en {categoryX}:\n[/][#fff font-size: 20px]{valueY.formatNumber('#.00')} Ha[/] [#fff]{additional}[/]";
    barPercentColumnSeries.columns.template.propertyFields.fillOpacity = "fillOpacity";
    barPercentColumnSeries.columns.template.propertyFields.stroke = "stroke";
    barPercentColumnSeries.columns.template.propertyFields.strokeWidth = "strokeWidth";
    barPercentColumnSeries.columns.template.propertyFields.strokeDasharray = "columnDash";
    barPercentColumnSeries.tooltip.label.textAlign = "middle";
    barPercentColumnSeries.fill = am4core.color("#fca311");
    barPercentColumnSeries.stroke = am4core.color("#fca311");

    let barPercentLineSeries = barPercentChart.series.push(new am4charts.LineSeries());
    barPercentLineSeries.name = "% de crecimiento del medio construido 2015-2020";
    barPercentLineSeries.dataFields.valueY = "inc";
    barPercentLineSeries.dataFields.categoryX = "region";
    barPercentLineSeries.yAxis = barPercentAxis;

    barPercentLineSeries.stroke = am4core.color("#c41e3a");
    barPercentLineSeries.strokeWidth = 3;
    barPercentLineSeries.propertyFields.strokeDasharray = "lineDash";
    barPercentLineSeries.tooltip.label.textAlign = "middle";

    let barPercentBullet = barPercentLineSeries.bullets.push(new am4charts.Bullet());
    barPercentBullet.fill = am4core.color("#c41e3a"); // tooltips grab fill from parent by default
    barPercentBullet.tooltipText = "[#fff font-size: 15px]{name}\n en {categoryX}:\n[/][#fff font-size: 20px]{valueY.formatNumber('#.00')} %[/] [#fff]{additional}[/]";

    let barPercentCircle = barPercentBullet.createChild(am4core.Circle);
    barPercentCircle.radius = 4;
    barPercentCircle.fill = am4core.color("#fff");
    barPercentCircle.strokeWidth = 3;

}); // end am4core.ready()