/*
 * kohinos_cooperatic
 * Copyright (C) 2019-2020  ADML63
 * Copyright (C) 2020- Cooperatic
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 /*
 * 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');

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

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

require('../js/geoloc.js');
// can be use to sort with drag'n drop in sonata admin
// require('../../public/bundles/pixsortablebehavior/js/init.js');

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

var $collectionHolder;
// setup an "add a groupe presta (marché amap" link
var $addGroupeButton = $('<button type="button" class="add_groupe_link">Ajouter AMAP / Marché</button>');
var $newLinkLi = $('<p></p>').append($addGroupeButton);

/* */
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></p>').append(newForm);
    $newLinkLi.before($newFormLi);
}

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){
    // prevent hiccup
    if ($(form).data('submitted') === true) {
      e.preventDefault();
    } else {
      $(form).data('submitted', true);
      form.submit()
    }
  });
  $('#confirmTransactionModal #dismissTransactionButton').on('click', function(e){
    $(form).data('submitted', false);
  });
  
}

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

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

	// 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'
  });

  /**
   * Display a confirmation modal for the 5 actions of a Comptoir
   */
  $('form[name^=formVente]')
  .add('form[name^=formRetrait]')
  .add('form[name=formTransfertPrestataireComptoir]')
  .on('submit', function (e) {
    // Stop form submition
    e.preventDefault();

    var form = this;

    if (form.checkValidity()) {
      var div = form.name === 'formTransfertPrestataireComptoir' ? '.confirmTransfertPrestataireComptoir' :
                form.name.includes('Prestataire')                ? '.confirmTransactionPrestataire'       :
                                                                   '.confirmTransactionAdherent'

      // Get expediteur or destinataire
      var select = $('#' + form.name + (form.name === 'formTransfertPrestataireComptoir' ? '_expediteur' : '_destinataire'))[0]
      var name = select.options[select.selectedIndex].text

      // Get montant
      var montant = $('#' + form.name + '_montant').val()

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