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

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

// amchart
am4core.ready(function() {

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

    // bar and line chart
    let chart = am4core.create("topLeftChart", am4charts.XYChart);

    let ctitle = chart.titles.create();
    ctitle.text = "Área urbanizada trimestralmente";
    ctitle.fontSize = 15;
    ctitle.fill = am4core.color(mainTextColor);

    // Create axes
    let xAxis = chart.xAxes.push(new am4charts.DateAxis());
    //xAxis.baseInterval = { timeUnit: "month", count: 3 };
    xAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    xAxis.renderer.labels.template.fontSize = 15;
    xAxis.renderer.labels.template.location = 0.5;
    /*xAxis.tooltipDateFormat = "q yyyy";
    xAxis.adapter.add("getTooltipText", (text) => {
        return "Q" + text;
    });*/
    //xAxis.dateFormats.setKey("month", "Qq yyyy");
    //xAxis.periodChangeDateFormats.setKey("month", "Qq yyyy");
    xAxis.renderer.grid.template.location = 0;
    //categoryAxis.renderer.line.strokeOpacity = 1;
    //categoryAxis.renderer.minGridDistance = 30;
    //xAxis.renderer.cellStartLocation = 0.2;
    //xAxis.renderer.cellEndLocation = 0.8;

    let valueAxisBars = chart.yAxes.push(new am4charts.ValueAxis());
    valueAxisBars.title.text = "Área urbanizada (Ha)";
    valueAxisBars.title.fill = am4core.color(mainTextColor);
    valueAxisBars.min = valueAxisBars.minZoomed;
    valueAxisBars.max = valueAxisBars.maxZoomed;
    valueAxisBars.title.fill = am4core.color(mainTextColor);
    valueAxisBars.renderer.labels.template.fill = am4core.color(mainTextColor);
    valueAxisBars.fontSize = 15;
    valueAxisBars.renderer.labels.template.fontSize = 15;
    valueAxisBars.numberFormatter = new am4core.NumberFormatter();
    valueAxisBars.numberFormatter.numberFormat = "#,###";

    let xAxisL = chart.xAxes.push(new am4charts.DateAxis());
    xAxisL.renderer.grid.template.location = 0;
    xAxisL.renderer.labels.template.disabled = true;
    xAxisL.renderer.grid.template.disabled = true;
    xAxisL.renderer.tooltip.disabled = true;
    /*xAxisL.baseInterval = { timeUnit: "month", count: 3 };
    xAxisL.renderer.labels.template.fontSize = 15;
    xAxisL.renderer.labels.template.location = 0.5;
    xAxisL.tooltipDateFormat = "q yyyy";
    xAxisL.adapter.add("getTooltipText", (text) => {
        return "Q" + text;
    });
    xAxisL.dateFormats.setKey("month", "Qq yyyy");
    xAxisL.periodChangeDateFormats.setKey("month", "Qq yyyy");
    xAxisL.renderer.grid.template.location = 0;
    xAxisL.renderer.cellStartLocation = 0.2;
    xAxisL.renderer.cellEndLocation = 0.8;*/

    let valueAxisL = chart.yAxes.push(new am4charts.ValueAxis());
    valueAxisL.title.text = "Porcentaje acumulado (%)";
    valueAxisL.renderer.opposite = true;
    valueAxisL.min = 0;
    valueAxisL.max = 100;
    valueAxisL.strictMinMax = true;
    //valueAxisL.render.grid.template.disabled = true;
    valueAxisL.numberFormatter = new am4core.NumberFormatter();
    valueAxisL.numberFormatter.numberFormat = "#'%'"
    valueAxisL.cursorTooltipEnabled = false;
    //valueAxisL.numberFormatter.numberFormat = "#.#";
    valueAxisL.renderer.labels.template.fill = am4core.color("#b9ce37");
    valueAxisL.title.fill = am4core.color("#b9ce37");
    //valueAxisL.min = -300;
    //valueAxisL.syncWithAxis = valueAxis1;
    valueAxisL.fontSize = 15;
    valueAxisL.renderer.labels.template.fontSize = 15;
    //valueAxisL.calculateTotals = true;

    // Modify chart's colors
    chart.colors.list = [
        am4core.color("#F18275"),
        am4core.color("#BB677C"),
        am4core.color("#7B5572"),
        am4core.color("#3E4157")
    ];

    const paretoData = data => {
        let total = 0,
            sum = 0,
            value;

        for (let i = 0; i < data.length; i++) {
            value = data[i].area;
            total += value;
        }
        for (let i = 0; i < data.length; i++) {
            value = data[i].area;
            sum += value;
            data[i].pareto = sum / total * 100;
        }
    }

    //Add data
    let table = "urbanization_year";
    let query = `${baseUrl}/query/${table}?columns=yeartrimes,sum(area)/10000 as area,date&group=yeartrimes,date&sort=yeartrimes`;
    d3.json(query).then( d => {
        paretoData(d);
        let chartData = d;

        [1, 2, 3, 4].forEach( q => {
            let series = chart.series.push(new am4charts.ColumnSeries());
            series.data = chartData.filter( d => Math.floor((new Date(d.date).getMonth() + 3) / 3) == q);
            series.dataFields.valueY = "area";
            series.dataFields.dateX = "date";
            series.xAxis = xAxis;
            series.yAxis = valueAxisBars;
            series.name = `Q${q}`;
            series.tooltipText = "[bold]Q{dateX.formatDate('q yyyy')}:[/]\nÁrea urbanizada: {valueY.formatNumber('#.#')} Ha";
            series.strokeWidth = 0;
        });

        let seriesL = chart.series.push(new am4charts.LineSeries());
        seriesL.data = chartData;
        seriesL.dataFields.dateX = "date";
        seriesL.dataFields.valueY = "pareto";
        seriesL.name = "Porcentaje acumulado";
        seriesL.xAxis = xAxisL;
        seriesL.yAxis = valueAxisL;
        seriesL.strokeOpacity = 0.5;
        seriesL.tensionX = 0.7;
        seriesL.stroke = am4core.color("#b9ce37");
        seriesL.tooltip.label.fontSize = 15;
        seriesL.tooltipText = "[bold]Q{dateX.formatDate('q yyyy')}:[/]\nIncremento acumulado de urbanización: {valueY.formatNumber('#.0')}% [/]\nIncremento urbanización: {valueY.previousChange.formatNumber('#.0')}%";
        seriesL.tooltip.getFillFromObject = false;
        seriesL.tooltip.background.fill = am4core.color(mainTextColor);
    });

    //Add cursor
    chart.cursor = new am4charts.XYCursor();
    // TODO: find a way to display bar and line tooltip.
    // only let one tooltip other wise we get one for each colun and line...
    chart.cursor.maxTooltipDistance = -1;

    //Add legend
    chart.legend = new am4charts.Legend();
    chart.legend.position = "top";
    chart.legend.fontSize = 15;
    chart.legend.labels.template.fill = am4core.color(mainTextColor);

    //Add scrollbar
    chart.scrollbarX = new am4charts.XYChartScrollbar();
    chart.scrollbarX.minHeight = 1;
    chart.scrollbarX.parent = chart.bottomAxesContainer;

    // pie chart

    let pchart = am4core.create("bottomLeftChart", am4charts.PieChart);

    let query2 = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,DATE_PART('year',date) as yy&group=yy&sort=yy`; // &sort=yeartrimes`;
    d3.json(query2).then(d => pchart.data = d);

    let ptitle = pchart.titles.create();
    ptitle.text = "Área urbanizada anualmente";
    ptitle.fontSize = 15;
    ptitle.marginTop = 30;
    ptitle.fill = am4core.color(mainTextColor);

    pchart.innerRadius = am4core.percent(40);
    //Add legend
    pchart.legend = new am4charts.Legend();
    pchart.legend.position = "right";
    pchart.legend.labels.template.fill = am4core.color(mainTextColor);
    pchart.legend.valueLabels.template.fill = am4core.color(mainTextColor);
    pchart.legend.fontSize = 15;

    // Add and configure Series
    let pieSeries = pchart.series.push(new am4charts.PieSeries());
    pieSeries.dataFields.value = "area";
    pieSeries.dataFields.category = "yy";
    pieSeries.ticks.template.disabled = true;
    //pieSeries.labels.template.disabled = true;
    pieSeries.alignLabels = false;
    pieSeries.labels.template.bent = true;
    pieSeries.colors.list = [
        am4core.color("#313695"),
        am4core.color("#5e6bbf"),
        am4core.color("#e0f3f8"),
        am4core.color("#ffffbf"),
        am4core.color("#b82a76"),
        am4core.color("#9e0142")
    ];
    pieSeries.slices.template.stroke = am4core.color("#ffffff");
    pieSeries.slices.template.strokeWidth = 3;
    pieSeries.slices.template.strokeOpacity = .20;
    pieSeries.slices.template.tooltipText = "[bold]{category}:[/] {value.percent.formatNumber('#.#')}% ({value.value.formatNumber('#,###.##')} Ha)";
    pieSeries.numberFormatter.numberFormat = "####.#";
    pieSeries.labels.template.fill = am4core.color(mainTextColor);
    pieSeries.labels.template.fontSize = 15;
    pieSeries.labels.template.text = "{category}";

    // radar chart
    //am4core.useTheme(am4themes_QQTheme);
    am4core.useTheme(am4themes_animated);

    // Themes end

    let rchart = am4core.create("bottomRightChart", am4charts.RadarChart);
    // chart.hiddenState.properties.opacity = 0; // this creates initial fade-in
    let query_r = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,DATE_PART('month',date) as mm,concat('Q', DATE_PART('quarter',date)::text) as qq&group=mm,qq &sort=mm`;

    d3.json(query_r).then(d => rchart.data = d);

    //chart.padding(20, 20, 20, 20);
    rchart.innerRadius = am4core.percent(15);
    rchart.radius = am4core.percent(90);
    //chart.data = weeklyData;
    rchart.fontSize = 12;
    rchart.startAngle = 180;
    rchart.endAngle = rchart.startAngle + 180;

    // Create axes
    // let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    let dateAxis = rchart.xAxes.push(new am4charts.CategoryAxis());
    dateAxis.dataFields.category = "qq";
    // dateAxis.baseInterval = { timeUnit: "month", count: 3 };
    //dateAxis.renderer.innerRadius = am4core.percent(40);
    dateAxis.renderer.minGridDistance = 5;
    dateAxis.renderer.labels.template.relativeRotation = 0;
    dateAxis.renderer.labels.template.location = 0.5;
    dateAxis.renderer.labels.template.radius = am4core.percent(-57);
    dateAxis.renderer.labels.template.fontSize = 12;
    dateAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    dateAxis.cursorTooltipEnabled = false;
    //  dateAxis.calculateTotals = true;

    let valueAxis = rchart.yAxes.push(new am4charts.ValueAxis());
    valueAxis.renderer.inversed = true;
    valueAxis.renderer.radius = am4core.percent(40);
    valueAxis.renderer.minGridDistance = 15;
    valueAxis.renderer.minLabelPosition = 0.05;
    //valueAxis.renderer.axisAngle = 90;
    valueAxis.renderer.axisAngle = 270;
    valueAxis.cursorTooltipEnabled = false;
    valueAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
    valueAxis.renderer.grid.template.stroke = am4core.color(mainTextColor);
    // valueAxis.calculateTotals = true;

    //Add series
    let columnSeries = rchart.series.push(new am4charts.RadarColumnSeries());

    // columnSeries.dataFields.dateX = "date";
    columnSeries.dataFields.categoryX = "qq"; //date
    columnSeries.dataFields.valueY = "area";
    // columnSeries.dataFields.valueYShow = "sum";
    columnSeries.columns.template.strokeOpacity = 0;
    columnSeries.columns.template.width = am4core.percent(95);

    //columnSeries.fill = am4core.color("#80acba");
    columnSeries.fillOpacity = 0.5;
    columnSeries.tooltip.fontSize = 15;
    columnSeries.tooltip.pointerOrientation = "down";
    columnSeries.tooltip.background.fillOpacity = 0.5;
    columnSeries.columns.template.tooltipText = "[bold]{qq}[/]\nTotal {valueY.formatNumber('#,###.##')} Ha";
    columnSeries.cursorTooltipEnabled = false;
    columnSeries.columns.template.adapter.add("fill", (fill, target) => {
        if (target.dataItem && (target.dataItem.categoryX == "Q1")) {
            return am4core.color("#F18275");
        } else if (target.dataItem && (target.dataItem.categoryX == "Q2")) {
            return am4core.color("#BB677C");
        } else if (target.dataItem && (target.dataItem.categoryX == "Q3")) {
            return am4core.color("#7B5572");
        } else if (target.dataItem && (target.dataItem.categoryX == "Q4")) {
            return am4core.color("#3E4157");
        } else {
            return fill;
        }
    });

    //ANILLO EXTERIOR
    let yearsAxis = rchart.yAxes.push(new am4charts.CategoryAxis());
    let bubbleSeries = rchart.series.push(new am4charts.RadarSeries());

    //let queryYYYY = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,DATE_PART('month',date) as mm,DATE_PART('year',date) as yy,date&group=yy,mm,date &sort=yy,mm`;
    let queryYYYY = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,to_char(to_timestamp (date_part('month', date)::text, 'MM'), 'Month') as mm,DATE_PART('year',date) as yy,concat('Q', DATE_PART('quarter',date)::text) as qq,date&group=qq,yy,mm,date &sort=date`;

    d3.json(queryYYYY).then(d => {
        yearsAxis.data = d
        bubbleSeries.data = d;
    });

    // weekday axis
    yearsAxis.dataFields.category = "yy";
    yearsAxis.renderer.innerRadius = am4core.percent(50);
    yearsAxis.renderer.minGridDistance = 10;
    yearsAxis.renderer.grid.template.location = 0;
    yearsAxis.renderer.grid.template.stroke = am4core.color(mainTextColor);
    yearsAxis.renderer.line.disabled = true;
    yearsAxis.renderer.axisAngle = 270;
    yearsAxis.cursorTooltipEnabled = false;
    yearsAxis.renderer.labels.template.fill = am4core.color(mainTextColor);

    yearsAxis.numberFormatter = new am4core.NumberFormatter();
    yearsAxis.numberFormatter.numberFormat = "####";

    // bubble series
    bubbleSeries.dataFields.categoryX = "qq";
    bubbleSeries.dataFields.categoryY = "yy";
    bubbleSeries.dataFields.value = "area";
    bubbleSeries.yAxis = yearsAxis;
    bubbleSeries.strokeOpacity = 0;
    bubbleSeries.maskBullets = false;
    bubbleSeries.cursorTooltipEnabled = false;
    bubbleSeries.tooltip.fontSize = 15;
    bubbleSeries.tooltip.pointerOrientation = "down";
    bubbleSeries.tooltip.background.fillOpacity = 0.5;
    bubbleSeries.dataItems.template.locations.categoryX = 0.5;

    let bubbleBullet = bubbleSeries.bullets.push(new am4charts.CircleBullet());
    bubbleBullet.locationX = 0.5;
    bubbleBullet.tooltipText = "[bold]Q{date.formatDate('q yyyy')}:[/] \n{value.formatNumber('#,###.0')} Ha";
    bubbleBullet.adapter.add("tooltipY", (tooltipY, target) => {
        return -target.circle.radius;
    });
    // TODO: Fix these calls to automatically use available years
    bubbleBullet.adapter.add("fill", (fill, target) => {
        if (target.dataItem && (target.dataItem.categoryY == "2014")) {
            return am4core.color("#313695");
        } else if (target.dataItem && (target.dataItem.categoryY == "2015")) {
            return am4core.color("#5e6bbf");
        } else if (target.dataItem && (target.dataItem.categoryY == "2016")) {
            return am4core.color("#e0f3f8");
        } else if (target.dataItem && (target.dataItem.categoryY == "2017")) {
            return am4core.color("#ffffbf");
        } else if (target.dataItem && (target.dataItem.categoryY == "2018")) {
            return am4core.color("#b82a76");
        } else if (target.dataItem && (target.dataItem.categoryY == "2019")) {
            return am4core.color("#9e0142");
        } else {
            return fill;
        }
    });
    // TODO: Fix these calls to automatically use available years
    bubbleBullet.adapter.add("stroke", (fill, target) => {
        if (target.dataItem && (target.dataItem.categoryY == "2014")) {
            return am4core.color("#313695");
        } else if (target.dataItem && (target.dataItem.categoryY == "2015")) {
            return am4core.color("#5e6bbf");
        } else if (target.dataItem && (target.dataItem.categoryY == "2016")) {
            return am4core.color("#e0f3f8");
        } else if (target.dataItem && (target.dataItem.categoryY == "2017")) {
            return am4core.color("#ffffbf");
        } else if (target.dataItem && (target.dataItem.categoryY == "2018")) {
            return am4core.color("#b82a76");
        } else if (target.dataItem && (target.dataItem.categoryY == "2019")) {
            return am4core.color("#9e0142");
        } else {
            return fill;
        }
    });

    bubbleSeries.heatRules.push({ target: bubbleBullet.circle, min: 2, max: 12, dataField: "value", property: "radius" });
    bubbleSeries.dataItems.template.locations.categoryY = 0.5;

    // TITULOS MISCELANEOS
    rchart.cursor = new am4charts.RadarCursor();
    rchart.cursor.innerRadius = am4core.percent(40);
    rchart.cursor.lineY.disabled = true;

    let label = rchart.radarContainer.createChild(am4core.Label);
    label.horizontalCenter = "middle";
    label.verticalCenter = "middle";
    label.fill = am4core.color(mainTextColor);
    label.fontSize = 13;
    //label.fontWeight = "bold";
    label.text = "TOTAL\nTRIMESTRAL";

    let title = rchart.createChild(am4core.Label);
    title.fill = am4core.color("#b9ce37");
    title.fontSize = 15;
    title.isMeasured = false;
    title.valign = "top";
    title.align = "left";
    title.wrap = true;
    title.width = 200;
    title.text = "[bold]Área urbanizada entre 2014 y 2019.\n[font-size:11; #ffffff] Cada círculo representa el tamaño del área urbanizada.";

}); // end am4core.ready()