<!--
  This Template use the GoGoCartoJs Library : https://gitlab.adullact.net/pixelhumain/GoGoCartoJs
  Documentation cna be found here https://pixelhumain.github.io/GoGoCartoJs/docs/configuration.html
  
  If you want to change something in the configuration, let's say the menu width, add a new parameter to bazarlist :
  {{ bazarliste id="2" template="gogocarto.tpl.html" menuwidth="500"}}
  Then you may to format or set defaults this new menuwidth parameter in BazarCarto::formatArguments
  So it will be available in this template with the code param['menuwidth']

  Then, find in gogocartoJs configuration how the property is defined. Here it's
  {
    menu: { width: 500 }
  }
  So edit, at the bottom of this file, the configuration given to GoGoCarto

  carto = goGoCarto('#gogo-map', {
    ....
    menu: { width: param['menuwidth'] }
    ...
  });

  Alternatively, for developers, they could provide a json configuration object url inside the "jsonconfurl" attribute, for example
  {{ bazarliste id="2" template="gogocarto.tpl.html" jsonconf="http://mysite/myCartoConf.json" }}
  This jsonconf will be merged with the template configuration (providing data, taxonomy etc...)

  TODO
  handle other params already used in map template : provider, latitude, longitude, zoom etc...
-->

<?php $GLOBALS['wiki']->AddCSSFile('styles/vendor/gogocarto/gogocarto.min.css'); ?>

<?php if (!empty($filters)) { ?>
  <div id="gogo-map<?php echo $params['nbbazarliste']; ?>"
          class="no-dblclick"
          style="<?php echo 'width:'.$params['width'].'; height:'.$params['height']; ?>"></div>
<?php } else { ?>
  <div class="alert alert-danger"><?php echo _t('BAZ_GOGO_NEED_GROUPS') ?></div>
<?php } ?>

<script>
  // wiki data to display
  var data = <?php echo json_encode($fiches) ?>;
  // All param attached in bazarlist action
  var param = <?php echo json_encode($params) ?>;
  // facettes filters
  var filters = <?php echo json_encode($filters) ?>;

  document.addEventListener("DOMContentLoaded",function() {
    // ----------------------------------------------------
    // Transform wiki data to better fit gogocarto ontology.
    // ----------------------------------------------------
    data = data.map(function(el) {
      el.taxonomy = []
      for(var field in filters) {
        if (el[field]) {
          el.taxonomy = el.taxonomy.concat(el[field].split(','))
          el[field] = null
        }
      }
      el.name = el.bf_titre;
      el.bf_titre = null;
      el.geo = {
        latitude: el.bf_latitude,
        longitude: el.bf_longitude
      }
      el.bf_latitude = null
      el.bf_longitude = null
      el.geolocation = null;
      el.html_data = null; 
      el.id_typeannonce = null;
      el.id = el.id_fiche
      el.id_fiche = null;
      el.statut_fiche = null

      // TODO display those one nicely in gogocarto
      el.owner = null
      el.url = null
      el.statut_fiche = null
      el.date_creation_fiche = null
      el.date_maj_fiche = null

      var result = { images: [] }
      for (var key in el) {
        var value = el[key]
        // remove attribute with empty value
        if (value) {
          // remove bf_ prefix
          if (key.indexOf('bf_') == 0) {
            var newkey = key.replace('bf_', '');
            result[newkey] = value;
          } else {
            result[key] = value;
          }
          if (key.indexOf('image') == 0 && key != 'images' && typeof(value) == 'string') {
            result.images.push(wiki.baseUrl.replace(/\?$/, '') + 'cache/image_' + value.toLowerCase());
            result[key] = null;
          }
        }
      }
      return result
    });

    // -------------------------------------
    // Transform wikiTaxo into gogocartoTaxo
    // -------------------------------------
    var gogoTaxo = [];
    
    let firstGroup = true
    for (var categoryId in filters) {
      var wikiCat = filters[categoryId];
      let useIconForMarker = categoryId == param['iconfield']
      let useColorForMarker = categoryId == param['colorfield']
      var gogoCat = {
        name:  wikiCat.title,
        isMandatory: false,
        showExpanded: !wikiCat.collapsed,
        useIconForMarker: useIconForMarker,
        useColorForMarker: useColorForMarker,
        options: wikiCat.list.map(wikiOption => {
          let gogoOption = {
            name: wikiOption.label,
            id: wikiOption.value
          }
          // Icon
          if (!param['iconfield'] && firstGroup)
            gogoOption.icon = "fa fa-bullseye"            
          else if (useIconForMarker) 
            gogoOption.icon = param['iconprefix'] + param['icon'][gogoOption.id]
          // Color
          if (!param['colorfield'] && firstGroup) 
            gogoOption.color = "#4e5056"
          else if (useColorForMarker) 
            gogoOption.color = param['color'][gogoOption.id]
          return gogoOption;
        })
      }
      firstGroup = false
      gogoTaxo.push(gogoCat);
    }

    // -------------------
    // Loads Configuration
    // -------------------
    var confReady = false; // sometime we need to download distant configuration
    gogoConf = {
      general: { activateHistoryStateAndRouting: false },
      language: 'fr',
      theme: 'flat',
      map: {
        defaultTileLayer: param['tilelayer'] || 'cartodb',
      },
      colors: {
        primary: "#d8604c",
        secondary: "#1a89a0",
        textDark: "#4e5056",
        textLight: "#ffffff",
      },
      data: {
        taxonomy: gogoTaxo,
        elements: data
      },
      fonts: {
        mainFont: 'Nunito'
      },
      menu: {
        width: 300 + (parseInt(param['filtercolsize']) - 3) * 30
      },
      features: {}
    }
    if (param['search'] == 'true' || param['search'] === true) {
        gogoConf.features.searchCategories = {};
        gogoConf.features.searchElements = {};
        gogoConf.features.searchGeolocate = {};
        gogoConf.features.searchPlace = {};
    }
    if (param['jsonconfurl']) {
      $.get(param['jsonconfurl'], function(distantConf) {
        gogoConf = { ...distantConf, ...gogoConf }
        confReady = true;
      });
    } else {
      confReady = true;
    }

    // Adds a timeout so me let jquery ending start, so when we load gogocarto there is no conflict
    setTimeout(() => {
      var jsElm = document.createElement("script");
      jsElm.type = "application/javascript";
      jsElm.src = window.location.origin + window.location.pathname + "javascripts/vendor/gogocarto/gogocarto.min.js";
      document.body.appendChild(jsElm);

      // When everything is ready, starts gogocarto
      interval = setInterval(function() {
        if (typeof goGoCarto != "undefined" && confReady) {
          carto = goGoCarto('#gogo-map<?php echo $params['nbbazarliste']; ?>', gogoConf)
          clearInterval(interval);
        }
      },100)
    }, 0)
  })
</script>

<style>
  /* hide facettes cuase we are using GoGoCarto facette equivalent*/
  .facette-container .filters-col, #search-form { display: none; }
  .facette-container .results-col { width: 100%; }

  @media (min-width: 800px) {
    .facette-container .results-col { padding: 0 15px; }
  }
  /* Fixs some style conflict */
  .gogo-load-css .gogo-theme-transiscope .iconInsideMarker-wrapper {
    background-color: transparent !important;
  }
  .gogo-load-css .subcategory-item.expanded .name-wrapper .arrow-after {
    border-color: transparent transparent #494745 transparent !important;
  }
  .gogo-load-css .subcategory-item:not(.expanded) .name-wrapper .arrow-after {
    border-color: #494745 transparent transparent transparent !important;
  }
  .gogo-load-css .gogocarto-container .subcategorie-option-item .icon:not(.fa) {
    line-height: 1.5;
  }
  .gogo-load-css .gogocarto-container .search-bar-autocomplete-results-container .label {
    display: inherit;
    padding: inherit;
    font-size: inherit ;
    font-weight: inherit;
    line-height: inherit;
    color: inherit;
    text-align: inherit;
    white-space: inherit;
    vertical-align: inherit;
    border-radius: inherit;
  }
  .gogo-load-css h1.element-title {
    color: inherit;
  }
  .dropdown-menu-right {
    right: 0;
    left: auto !important;
  }
  <?php if (!isset($params['search']) || !$params['search']) { ?>
    .directory-menu-header .btn-close-menu { 
      display: none !important; 
    }
 <?php }?>
</style>
