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

/* globals am4core, am4charts, am4themes_animated, intervals*/

// amchart
am4core.ready(function() {
    //  am4core.useTheme(urban_theme);


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

    // bar and line chart

    var chart = am4core.create("topChart", am4charts.XYChart);

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

    //Add data
    const baseUrl = new URL(`/data`, window.location.href).href;
    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 => {
        chart.data = d;
        ParetoData()
    });

    // 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");

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


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

    // Modify chart's colors
    /*  chart.colors.list = [
          am4core.color("#313695"),
          am4core.color("#313695"),
          am4core.color("#313695"),
          am4core.color("#5e6bbf"),
          am4core.color("#5e6bbf"),
          am4core.color("#5e6bbf"),
          am4core.color("#5e6bbf"),
          am4core.color("#e0f3f8"),
          am4core.color("#e0f3f8"),
          am4core.color("#e0f3f8"),
          am4core.color("#e0f3f8"),
          am4core.color("#ffffbf"),
          am4core.color("#ffffbf"),
          am4core.color("#ffffbf"),
          am4core.color("#ffffbf"),
          am4core.color("#b82a76"),
          am4core.color("#b82a76"),
          am4core.color("#b82a76"),
          am4core.color("#9e0142"),
          am4core.color("#9e0142"),
          am4core.color("#9e0142"),
          am4core.color("#9e0142"),
      ];*/

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





    function ParetoData() {
        console.log(chart.data)

        var total = 0;

        for (var i = 0; i < chart.data.length; i++) {
            var value = chart.data[i].area;
            total += value;
        }

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

        }

    }



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

    // valueAxis3.numberFormatter = new am4core.NumberFormatter();
    // valueAxis3.numberFormatter.numberFormat = "#,###";

    //valueAxis3.syncWithAxis = valueAxis1;

    // Create series
    let series1 = chart.series.push(new am4charts.ColumnSeries());
    series1.dataFields.dateX = "date";
    series1.dataFields.valueY = "area";
    series1.name = "Área urbanizada";
    series1.yAxes = valueAxis1;
    //series1.tooltipText = "{name}\n{dateX}:\n[bold font-size: 20] {valueY}"; //"{name}\n[bold font-size: 20]{valueY}"; //M[/]";
    // series1.tooltipText = "[bold font-size: 20]{name}\n[bold font-size: 20] {valueY.formatNumber('#,###.#')} Ha";
    series1.fill = chart.colors.getIndex(0);
    series1.strokeWidth = 0;
    series1.clustered = false;
    series1.tooltipText = "[bold]Q{dateX.formatDate('q yyyy')}:[/]\nÁrea urbanizada: {valueY.formatNumber('#.#')} Ha";

    //series1.tooltipText = "[{categoryX}: bold]{valueY.formatNumber('#.0')} Ha[/]";


    series1.columns.template.adapter.add("fill", function(fill, target) {
        return chart.colors.getIndex(target.dataItem.index);
    })


    let series3 = chart.series.push(new am4charts.LineSeries());
    series3.dataFields.valueY = "pareto"; //"area";
    //series3.dataFields.valueYShow = "pareto"; //previousChangePercent";
    series3.dataFields.dateX = "date";
    series3.name = "Porcentaje acumulado";
    series3.yAxis = valueAxis3;
    series3.tooltipText = "pareto: {valueY.formatNumber('#.0')}%[/]";
    //series3.bullets.push(new am4charts.CircleBullet());
    //series3.strokeWidth = 2;
    //series3.stroke = new am4core.InterfaceColorSet().getFor("alternativeBackground");
    series3.strokeOpacity = 0.5;
    //series3.strokeWidth = 2;
    series3.tensionX = 0.7;
    series3.stroke = am4core.color("#b9ce37");
    //series3.strokeDasharray = "3,3";
    //series3.yAxis = valueAxis3;
    series3.tooltip.label.fontSize = 15;
    series3.tooltipText = "[bold]Q{dateX.formatDate('q yyyy')}:[/]\nIncremento acumulado de urbanización: {valueY.formatNumber('#.0')}% [/]\nIncremento urbanización: {valueY.previousChange.formatNumber('#.0')}%";
    series3.tooltip.getFillFromObject = false;
    series3.tooltip.background.fill = am4core.color(mainTextColor);


    //Add cursor
    chart.cursor = new am4charts.XYCursor();

    //Add legend
    chart.legend = new am4charts.Legend();
    chart.legend.position = "top";
    chart.legend.fontSize = 15;
    chart.legend.labels.template.fill = am4core.color(mainTextColor);
    //chart.legend.markers.template.disabled = true;
    //chart.legend.labels.template.text = "Series: [bold {color}]{name}[/]";


    var legenddata = [{ name: "Q1", fill: am4core.color("#F18275") },
        { name: "Q2", fill: am4core.color("#BB677C") },
        { name: "Q3", fill: am4core.color("#7B5572") },
        { name: "Q4", fill: am4core.color("#3E4157") },
        { name: "Porcentaje acumulado", fill: am4core.color("#b9ce37"), marker: "line" }
    ];

    chart.legend.data = legenddata;

    //Add scrollbar
    // chart.legend.labels.template.fill = am4core.color(mainTextColor);
    chart.scrollbarX = new am4charts.XYChartScrollbar();
    // chart.scrollbarX.series.push(series3);
    chart.scrollbarX.minHeight = 1;

    //chart.scrollbarX.series.push(series3);
    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

    var rchart = am4core.create("bottomRightChart", am4charts.RadarChart);
    // chart.hiddenState.properties.opacity = 0; // this creates initial fade-in

    //const baseUrl = new URL(`/data`, window.location.href).href;
    //let table = "urbanization_year";
    //let query = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,date,DATE_PART('month',date) as mm&group=mm,date &sort=mm`;
    //let query = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,DATE_PART('month',date) as mm&group=mm &sort=mm`;
    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
    // var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    var 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;

    var 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
    var 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", function(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
     var range = dateAxis.axisRanges.create();
     range.category = "January";
     range.endCategory = "April";
     range.axisFill.fill = am4core.color("#396478");
     range.axisFill.fillOpacity = 0.3;*/

    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
    //var weekDayAxis = chart.yAxes.push(new am4charts.CategoryAxis());
    yearsAxis.dataFields.category = "yy";
    //yearsAxis.data = dailyData;
    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
    //var bubbleSeries = chart.series.push(new am4charts.RadarSeries());
    bubbleSeries.dataFields.categoryX = "qq";
    bubbleSeries.dataFields.categoryY = "yy";
    bubbleSeries.dataFields.value = "area";
    bubbleSeries.yAxis = yearsAxis;
    //bubbleSeries.data = dailyData;
    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;

    var bubbleBullet = bubbleSeries.bullets.push(new am4charts.CircleBullet())
    bubbleBullet.locationX = 0.5;
    //bubbleBullet.stroke = am4core.color(mainTextColor);
    //bubbleBullet.fill = am4core.color("#b9ce37");
    bubbleBullet.tooltipText = "[bold]Q{date.formatDate('q yyyy')}:[/] \n{value.formatNumber('#,###.0')} Ha";
    bubbleBullet.adapter.add("tooltipY", function(tooltipY, target) {
        return -target.circle.radius;
    })
    bubbleBullet.adapter.add("fill", function(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;
        }
    });
    bubbleBullet.adapter.add("stroke", function(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;

    var 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";

    var 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()