/*
 * Welcome to your app's main JavaScript file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you require will output into a single css file (app.css in this case)

// UTILISER LES FONT AWESOME POUR L'ICONOGRAPHIE
require('../../public/fontawesome/css/all.min.css');
// CSS DU KOHINOS
require('../css/app.css');
// THEME BOOTSTRAP / BOOTSWATCH + CONFIGURATION GLOBALE (COULEURS, FONTS...)
require('../css/global.scss');

// Need jQuery? Install it with "yarn add jquery", then uncomment to require it.
// require jQuery normally
const $ = require('jquery');

// create global $ and jQuery variables
global.$ = global.jQuery = $;

// JS is equivalent to  the normal "bootstrap" package
// no need to set this to a variable, just require it
// require('popper.js/dist/popper.js');
require('bootstrap');

require('../css/common.css');
// BOOTSTRAP plugins
require('bootstrap-slider')
require('bootstrap-slider/dist/css/bootstrap-slider.min.css')

// @TODO : make boostrap-datepicker works !!
// require('bootstrap-datepicker-webpack')
// require('bootstrap-datepicker-webpack/dist/css/bootstrap-datepicker3.min.css')
// require('../../public/bundles/sonatacore/vendor/moment/min/moment-with-locales.min.js');
// require('../../public/bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js');
// require('../../public/bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css');

// leaftlet : for openstreetmap
require('../leaflet/leaflet.js');
// for flash message notification
require('../js/flash-messages.js');

require('../js/geoloc.js');

$('#flash-messages').flashNotification('init');

var $collectionHolder;
// setup an "add a groupe presta (marché amap" link
var $addGroupeButton = $('<button type="button" class="btn btn-secondary add_groupe_link"><i class="fa fa-plus-circle" aria-hidden="true"></i> Ajouter AMAP / Marché</button>');
var $newLinkLi = $('<p class="row mx-2"></p>').append($addGroupeButton);
var $addGeolocButton = $('<button type="button" class="btn btn-secondary add_groupe_link"><i class="fa fa-plus-circle" aria-hidden="true"></i> Ajouter Adresse</button>');
var $newLinkLiGeoloc = $('<p class="row mx-2"></p>').append($addGeolocButton);

/* */
function addGroupeForm($collectionHolder, $newLinkLi) {
    // Get the data-prototype explained earlier
    var prototype = $collectionHolder.data('prototype');

    // get the new index
    var index = $collectionHolder.data('index');

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newForm = prototype.replace(/__name__/g, index);

    // increase the index with one for the next item
    $collectionHolder.data('index', index + 1);

    // Display the form in the page in an li, before the "Add a groupe" link li
    var $newFormLi = $('<p class="row mx-2"></p>').append(newForm);
    $newLinkLi.before($newFormLi);

    // add a delete link to the new form
    addGroupeFormDeleteLink($newFormLi);
}

function addGroupeFormDeleteLink($tagFormLi) {
    var $removeFormButton = $('<button type="button" class="col-3 btn btn-warning">Supprimer</button>');
    $tagFormLi.append($removeFormButton);

    $removeFormButton.on('click', function(e) {
        // remove the li for the tag form
        $tagFormLi.remove();
    });
}


/* */
function addGroupeFormGeoloc($collectionHolderGeoloc, $newLinkLiGeoloc) {
    // Get the data-prototype explained earlier
    var prototypeGeoloc = $collectionHolderGeoloc.data('prototype');

    // get the new index
    var indexGeoloc = $collectionHolderGeoloc.find('.form-group').length;

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newFormGeoloc = prototypeGeoloc.replace(/__name__/g, indexGeoloc);

    // increase the index with one for the next item
    $collectionHolderGeoloc.data('index', indexGeoloc + 1);

    // Display the form in the page in an li, before the "Add a groupe" link li
    var $newFormLiGeoloc = $('<p></p>').append(newFormGeoloc);
    $newLinkLiGeoloc.before($newFormLiGeoloc);

    // add a delete link to the new form
    addGroupeFormDeleteLinkGeoloc($newFormLiGeoloc);
}

function addGroupeFormDeleteLinkGeoloc($tagFormLiGeoloc) {
    var $removeFormButtonGeoloc = $('<button type="button" class="btn btn-warning">Supprimer</button>');
    $tagFormLiGeoloc.append($removeFormButtonGeoloc);

    $removeFormButtonGeoloc.on('click', function(e) {
        // remove the li for the tag form
        $tagFormLiGeoloc.remove();
    });
}

function showConfirmTransactionModal(div, form, montant, destinataire = null) {
  // Get modal
  var modal = $('#confirmTransactionModal')

  // Get relevant confirmation message div
  var message = modal.find(div)

  // Set data in modal
  message.find('.montant_transaction').text(montant)
  if (destinataire != null) {
    message.find('.nom_destinataire').text(destinataire)
  }

  // Show modal and relevant confirmation message
  modal.find(div).show()
  modal.modal('show')

  // Bind modal validation button with form submition
  $('#confirmTransactionModal #confirmTransactionButton').off()
  $('#confirmTransactionModal #confirmTransactionButton').on('click', function(e){
    form.submit()
  });
}

jQuery(document).ready(function() {
	// Get the ul that holds the collection of groupes
	$collectionHolder = $('.groupeprestas');

	// add a delete link to all of the existing tag form li elements
    $collectionHolder.find('div.form-group').each(function() {
    	$(this).addClass('row mx-2');
        addGroupeFormDeleteLink($(this));
    });

	// add the "add a groupe" anchor and li to the groupes ul
	$collectionHolder.append($newLinkLi);

	// count the current form inputs we have (e.g. 2), use that as the new
	// index when inserting a new item (e.g. 2)
	$collectionHolder.data('index', $collectionHolder.find(':input').length);

	$addGroupeButton.on('click', function(e) {
	    // add a new groupe form (see next code block)
	    addGroupeForm($collectionHolder, $newLinkLi);
	});

	// Get the ul that holds the collection of groupes
	$collectionHolderGeoloc = $('.geolocs');

	// add a delete link to all of the existing tag form li elements
    $collectionHolderGeoloc.find('li').each(function() {
        addGroupeFormDeleteLinkGeoloc($(this));
    });

	// add the "add a groupe" anchor and li to the groupes ul
	$collectionHolderGeoloc.append($newLinkLiGeoloc);

	// count the current form inputs we have (e.g. 2), use that as the new
	// index when inserting a new item (e.g. 2)
	$collectionHolderGeoloc.data('index', $collectionHolderGeoloc.find(':input').length);

	$addGeolocButton.on('click', function(e) {
	    // add a new groupe form (see next code block)
	    addGroupeFormGeoloc($collectionHolderGeoloc, $newLinkLiGeoloc);
	});

	// BOOTSTRAP TOOLTIPS
	$('[data-toggle="tooltip"]').tooltip()

  $("input:radio[name='formAchatMonnaieAdherent[montantradio]']").change(function() {
    var mySlider = $("input.achatmonnaie-montant-slider").slider();

    // Set slider value like radio when radio changes
  	mySlider.slider('setValue', this.value)

    $("span.achat_monnaie_montant_choisi").text(this.value + ' €')
  });

  $('input.achatmonnaie-montant-slider').slider().on('change', function(event){
      var value = event.value.newValue;

      $("span.achat_monnaie_montant_choisi").text(value + ' €')
  });

  $('.transactionSubmit').on('click', function(e){
      // Stop form submition
      e.preventDefault();

      var form = this.closest('form')
      if (form.checkValidity()) {
        // Get destinataire type : presta or adherent
        var destinataire_type = $('#' + form.name + '_destinataireType')[0].value
        if (destinataire_type == 'prestataire') {
          var div = '.confirmTransactionPrestataire'
        } else {
          var div = '.confirmTransactionAdherent'
        }

        // Get destinataire
        var destinataire_select = $('#' + form.name + '_destinataire')[0]
        var destinataire_name = destinataire_select.options[destinataire_select.selectedIndex].text

        // Get montant
        var montant_field = $('#' + form.name + '_montant')[0]
        var montant_value = montant_field.value

        showConfirmTransactionModal(div, form, montant_value, destinataire_name)
      } else {
        // Use symfony validation
        form.submit()
      }
  });

  $('.cotisationMLCSubmit').on('click', function(e){
      // Stop form submition
      e.preventDefault();

      var form = this.closest('form')

      // Set form moyen
      $('#' + form.name + '_moyen')[0].value = 'mlc'

      if (form.checkValidity()) {
        var div = '.confirmCotisation'

        // Get montant
        var montant_field = $('#' + form.name + '_montant')[0]
        var montant_value = montant_field.value

        showConfirmTransactionModal(div, form, montant_value)
      } else {
        // Use symfony validation
        form.submit()
      }
  });
  $('.cotisationCBSubmit').on('click', function(e){
      var form = this.closest('form')

      // Set form moyen
      $('#' + form.name + '_moyen')[0].value = 'cb'
  });

  $("input:radio[name='formAchatMonnaieAConfirmerAdherent[moyen]']").change(function() {
    if ($("#demande_achat_text_"+this.value).length) {
      $(".demande_achat_text").hide();
      $("#demande_achat_text_"+this.value).show();
    }
  });

  $("input:radio[name='formAchatMonnaieAConfirmerPrestataire[moyen]']").change(function() {
    if ($("#demande_achat_text_"+this.value).length) {
      $(".demande_achat_text").hide();
      $("#demande_achat_text_"+this.value).show();
    }
  });

  // $('.js-datepicker').datepicker({
  //     closeText: 'Fermer',
  //     prevText: '&#x3c;Préc',
  //     nextText: 'Suiv&#x3e;',
  //     currentText: 'Aujourd\'hui',
  //     monthNames: ['Janvier','Fevrier','Mars','Avril','Mai','Juin',
  //     'Juillet','Aout','Septembre','Octobre','Novembre','Decembre'],
  //     monthNamesShort: ['Jan','Fev','Mar','Avr','Mai','Jun',
  //     'Jul','Aou','Sep','Oct','Nov','Dec'],
  //     dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
  //     dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
  //     dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
  //     weekHeader: 'Sm',
  //     dateFormat: 'yy-mm-dd',
  //     format: 'yyyy-mm-dd',
  //     firstDay: 1,
  //     isRTL: false,
  //     showMonthAfterYear: false,
  //     yearSuffix: '',
  //     minDate: 0,
  //     maxDate: '+12M +0D',
  //     numberOfMonths: 2,
  //     showButtonPanel: true
  // });

});