<!-- Styles -->
<style>
  #chartdiv {
    width: 100%;
    height: 650px;
  }
</style>

<!-- HTML -->
<div id="chartdiv"></div>

<!-- Resources -->
<script src="ammap/amcharts4/core.js"></script>
<script src="ammap/amcharts4/maps.js"></script>
<script src="ammap/amcharts4/geodatacore/worldHigh.js"></script>
<script src="ammap/amcharts4/geodatacore/kurdistanLow.js"></script>
<script src="ammap/amcharts4/themes/animated.js"></script>
<script src="ammap/country-population.js"></script>
<script src="ammap/ethnicities.js"></script>

<!-- Chart code -->
<script>
  // colors
  // var hovercolor = "#0975da";
  // var strokecolor = "#30384f";
  // var smallmapbgcolor = "#4d5773";
  // var fillcolor = "#222a3f";
  // colors
  var hovercolor = "#c0ecae";
  var strokecolor = "#acb0c9";
  var smallmapbgcolor = "#ffffff";
  var fillcolor = "#f2f1f0";
  var fillcolor2 = "#efebe8";

  // var mainContainer = am4core.create("chartdiv", am4core.Container);
  // mainContainer.background.fillOpacity = 1;
  // mainContainer.background.fill = am4core.color("#313950");
  // mainContainer.width = am4core.percent(100);
  // mainContainer.height = am4core.percent(100);
  // mainContainer.preloader.disabled = true;

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

  /* Create map instance */
  var chart = am4core.create("chartdiv", am4maps.MapChart);

  /* Set map definition */
  chart.geodata = am4geodata_worldHigh;

  /* Set projection */
  chart.projection = new am4maps.projections.Mercator();

  /* Create map polygon series */
  var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());

  /* Make map load polygon (like country names) data from GeoJSON */
  polygonSeries.useGeodata = true;

  /* Configure series */
  var polygonTemplate = polygonSeries.mapPolygons.template;
  polygonTemplate.applyOnClones = true;
  polygonTemplate.togglable = true;
  polygonSeries.data = countriesPopulation;
  polygonTemplate.tooltipText = `[bold]{name}[/] {population}{tooltipcontent}`;
  polygonTemplate.nonScalingStroke = true;
  polygonTemplate.strokeOpacity = 0.4;
  polygonTemplate.fill = am4core.color(fillcolor);
  polygonTemplate.stroke = am4core.color(strokecolor);

  polygonSeries.heatRules.push({
    property: "fill",
    target: polygonSeries.mapPolygons.template,
    min: am4core.color(hovercolor).brighten(1),
    max: am4core.color(hovercolor).brighten(-0.3)
  });

  var lastSelected;
  var citiesSeries;
  polygonTemplate.events.on("hit", function(ev) {
    if (lastSelected) {
      // This line serves multiple purposes:
      // 1. Clicking a country twice actually de-activates, the line below
      //    de-activates it in advance, so the toggle then re-activates, making it
      //    appear as if it was never de-activated to begin with.
      // 2. Previously activated countries should be de-activated.
      lastSelected.isActive = false;
    }

    ev.target.series.chart.zoomToMapObject(ev.target);
    if (lastSelected !== ev.target) {
      lastSelected = ev.target;
    }

    if (chart.series.indexOf(citiesSeries) > -1) {
      chart.series.removeIndex(chart.series.indexOf(citiesSeries));
    }

    var name = ev.target.dataItem.dataContext.name.toLowerCase().replace(',', '').replace('.', '');
    var newname;
    if (/\s/.test(name)) {
      var arrname = name.split(' ');
      newname = arrname[0] + arrname[1].charAt(0).toUpperCase() + arrname[1].slice(1) + 'Low.json';
    } else {
      newname = name + 'Low.json';
    }

    jQuery.getJSON('ammap/amcharts4/geodata/json/' + newname, function(data) {
      citiesSeries = chart.series.push(new am4maps.MapPolygonSeries());
      citiesSeries.geodata = data;

      var citiesPolygonTemplate = citiesSeries.mapPolygons.template;
      citiesPolygonTemplate.tooltipText = "{name}: {id}";
      citiesPolygonTemplate.fill = am4core.color(hovercolor);
      citiesPolygonTemplate.stroke = am4core.color(strokecolor);
      citiesPolygonTemplate.nonScalingStroke = true;
    })
  })

  /* Create selected and hover states and set alternative fill color */
  // var ss = polygonTemplate.states.create("active");
  // ss.properties.fill = am4core.color(hovercolor);

  var hs = polygonTemplate.states.create("hover");
  hs.properties.stroke = am4core.color(strokecolor).brighten(-0.6);

  // Hide Antarctica
  polygonSeries.exclude = ["AQ"];

  // Small map
  chart.smallMap = new am4maps.SmallMap();
  // Re-position to top right (it defaults to bottom left)
  chart.smallMap.align = "right";
  chart.smallMap.valign = "top";
  chart.smallMap.series.push(polygonSeries);
  chart.smallMap.background.stroke = am4core.color(strokecolor);
  chart.smallMap.background.strokeOpacity = 0;
  chart.smallMap.background.fill = am4core.color(smallmapbgcolor);
  chart.smallMap.background.fillOpacity = 0.5;

  // Zoom control
  chart.zoomControl = new am4maps.ZoomControl();

  var homeButton = new am4core.Button();
  homeButton.events.on("hit", function() {
    chart.goHome();
  });

  homeButton.icon = new am4core.Sprite();
  homeButton.padding(7, 5, 7, 5);
  homeButton.width = 30;
  homeButton.icon.path = "M16,8 L14,8 L14,16 L10,16 L10,10 L6,10 L6,16 L2,16 L2,8 L0,8 L8,0 L16,8 Z M16,8";
  homeButton.marginBottom = 10;
  homeButton.parent = chart.zoomControl;
  homeButton.insertBefore(chart.zoomControl.plusButton);

  let linkContainer = chart.createChild(am4core.Container);
  linkContainer.isMeasured = false;
  linkContainer.layout = "horizontal";
  linkContainer.x = am4core.percent(20);
  linkContainer.y = am4core.percent(5);
  linkContainer.horizontalCenter = "middle";

  let mercator = linkContainer.createChild(am4core.TextLink);
  mercator.text = "Mercator";
  mercator.margin(10, 10, 10, 10);
  mercator.events.on("hit", function() {
    chart.projection = new am4maps.projections.Mercator();
  })

  let miller = linkContainer.createChild(am4core.TextLink);
  miller.margin(10, 10, 10, 10);
  miller.text = "Miller";
  miller.events.on("hit", function() {
    chart.projection = new am4maps.projections.Miller();
  })

  let orthographic = linkContainer.createChild(am4core.TextLink);
  orthographic.margin(10, 10, 10, 10);
  orthographic.text = "Orthographic";
  orthographic.events.on("hit", function() {
    chart.projection = new am4maps.projections.Orthographic();
  })

  let slider = chart.chartContainer.createChild(am4core.Slider);
  slider.start = 0.5;
  slider.valign = "bottom";
  slider.width = 400;
  slider.align = "center";
  slider.marginBottom = 15;
  slider.start = 0.05;
  slider.events.on("rangechanged", () => {
    chart.deltaLongitude = 360 * slider.start;
  })
</script>

<script>
  var kurdistanSeries;

  $("body").on("click", ".mapEthnicityClick", function(e) {

    chart.goHome();

    if (chart.series.indexOf(citiesSeries) > -1) {
      chart.series.removeIndex(chart.series.indexOf(citiesSeries));
    }

    // if (chart.series.indexOf(citiesSeriesProv) > -1) {
    //   chart.series.removeIndex(chart.series.indexOf(citiesSeriesProv));
    // }

    var ethnicityOrgString = $(this).data('ethnicity');

    if (!ethnicityOrgString) {
      return
    }

    var selectedEthnicities = [];
    var index = 0;
    ethnicityOrgString.split('%) ').forEach(ethnicity => {
      index++;
      var ethnicityItem = ethnicity.split('(');

      var ethnicityObj = {
        name: ethnicityItem[0].trim().replace('%', '').replace(' ', '-').replace(')', ''),
        value: ethnicityItem[1].trim().replace('%', '').replace(' ', '-').replace(')', ''),
        color: chart.colors.getIndex(index),
        index: index,
        countries: []
      }

      var ethnicityData = ethnicitiesData.find(function(element) {
        return element.ethnicity.replace('-ethnicity', '').toLowerCase() === ethnicityObj.name.replace(' ', '-').toLowerCase();
      });

      if (ethnicityData && ethnicityData.Countries) {
        ethnicityObj.countries = ethnicityData.Countries;
      } else {
        ethnicityObj.countries = [];
      }
      selectedEthnicities.push(ethnicityObj);
    });

    var heatData = [];

    selectedEthnicities.forEach(selectedEthincity => {
      var totalPopulationUndefinedCountries = 0;
      var totalPredefinedCountriesPercent = 0;
      var remainCountryPercent = 0;
      var onePercentOfPopulationUndefinedCountries = 0;
      var countryPopulation = 0;
      var colorValue = 0;

      selectedEthincity.countries.forEach(country => {
        if (typeof country === 'string') {
          var i = countriesPopulation.findIndex(function(item) {
            return item.id === country
          });

          if (countriesPopulation[i] && countriesPopulation[i].population) {
            countryPopulation = countriesPopulation[i].population;
          } else {
            countryPopulation = 1;
          }

          totalPopulationUndefinedCountries += countryPopulation;
        }

        if (typeof country === 'object') {

          var countryValue = 0;
          if (country.value && country.value > 0) {
            countryValue = country.value;
          } else {
            countryValue = 1;
          }
          
          totalPredefinedCountriesPercent += countryValue;
        }
      });

      remainCountryPercent = 100 - parseInt(totalPredefinedCountriesPercent, 0);

      onePercentOfPopulationUndefinedCountries = totalPopulationUndefinedCountries / remainCountryPercent;

      var checkDuplicateCountries = [];
      selectedEthincity.countries.forEach(country => {

        var heatObj = {};
        if (typeof country === 'string') {

          if (checkDuplicateCountries.includes(country)) {
            return;
          }

          checkDuplicateCountries.push(country);

          var i = countriesPopulation.findIndex(function(item) {
            return item.id === country
          });

          if (countriesPopulation[i] && countriesPopulation[i].population) {
            countryPopulation = countriesPopulation[i].population;
          } else {
            countryPopulation = 1;
          }
          
          colorValue = countryPopulation / onePercentOfPopulationUndefinedCountries;

          heatObj = {
            id: country,
            population: 0,
            value: parseInt(Math.round(colorValue * (selectedEthincity.value / 100))),
            probability: parseInt(Math.round(colorValue * (selectedEthincity.value / 100))),
            selectedEthincityName: selectedEthincity.name,
            selectedEthincityValue: selectedEthincity.value,
            tooltipcontent: "\r\nProbability " + Math.round(colorValue * (selectedEthincity.value / 100)) + "%\r\nETHNICITY:\r\n" + selectedEthincity.name + " " + selectedEthincity.value + "%"
          }

          heatData.push(heatObj);
        }


        if (typeof country === 'object' && country.hasOwnProperty('parentId')) {

          var countryPopulation = countriesPopulation.find(function(obj) {
            return obj.id === country.parentId
          })

          var newname = countryPopulation.name.toLowerCase() + 'Low.json';

          var citiesHeatData = [];

          jQuery.getJSON('ammap/amcharts4/geodata/json/' + newname, function(data) {

            var citiesSeriesProv = chart.series.push(new am4maps.MapPolygonSeries());
            citiesSeriesProv.heatRules.push({
              property: "fill",
              target: citiesSeriesProv.mapPolygons.template,
              min: am4core.color(hovercolor).brighten(1),
              max: am4core.color(hovercolor).brighten(-0.3)
            });
            citiesSeriesProv.geodata = data;

            var citiesPolygonTemplate = citiesSeriesProv.mapPolygons.template;
            citiesPolygonTemplate.tooltipText = "{name}: {id}";
            citiesPolygonTemplate.fill = am4core.color(fillcolor2);
            citiesPolygonTemplate.stroke = am4core.color(strokecolor);
            citiesPolygonTemplate.nonScalingStroke = true;


            var valueOfColor = 100000000;
            country.Provinces.forEach(prov => {
              var heatObjProv = {
                id: prov,
                value: valueOfColor
              }
              valueOfColor -= 10;
              citiesHeatData.push(heatObjProv);
            });

            citiesSeriesProv.data = citiesHeatData;
          })
        }

        if (typeof country === 'object' && !country.hasOwnProperty('parentId')) {

          if (checkDuplicateCountries.includes(country.id)) {
            return;
          }

          checkDuplicateCountries.push(country.id);

          var i = countriesPopulation.findIndex(function(item) {
            return item.id === country.id
          });

          if (countriesPopulation[i] && countriesPopulation[i].population) {
            countryPopulation = countriesPopulation[i].population;
          } else {
            countryPopulation = 1;
          }

          heatObj = {
            id: country.id,
            population: 0,
            value: Math.round(country.value * (selectedEthincity.value / 100)),
            probability: Math.round(country.value * (selectedEthincity.value / 100)),
            selectedEthincityName: selectedEthincity.name,
            selectedEthincityValue: selectedEthincity.value,
            tooltipcontent: "\r\nProbability " + Math.round(country.value * (selectedEthincity.value / 100)) + "%\r\nETHNICITY:\r\n" + selectedEthincity.name + " " + selectedEthincity.value + "%"
          }

          heatData.push(heatObj);
        }
      });
      
    });



    var i = selectedEthnicities.findIndex(function(item) {
      return item.name === 'Kurdish'
    });

    if (i > -1) {
      kurdistanSeries = chart.series.push(new am4maps.MapPolygonSeries());
      kurdistanSeries.geodata = am4geodata_kurdistanLow;

      var kurdistanTemplate = kurdistanSeries.mapPolygons.template;
      kurdistanTemplate.tooltipText = "{name} 25,000,000";
      kurdistanTemplate.fill = chart.colors.getIndex(2);
      kurdistanTemplate.fillOpacity = 0.4;
      kurdistanTemplate.stroke = chart.colors.getIndex(2);
    } else {
      if (chart.series.indexOf(kurdistanSeries) > -1) {
        chart.series.removeIndex(chart.series.indexOf(kurdistanSeries));
      }
    }

    var newlist = [];
    countriesPopulation.forEach(element => {
      var i = heatData.findIndex(function(item) {
        return item.id === element.id
      });
      if (i > -1) {
        heatData[i].population = element.population;
        newlist.push(heatData[i]);
      } else {
        newlist.push(element);
      }
    });

    polygonSeries.data = newlist;
  });
</script>