// dictionary: deveui as key, count as value
var abos_to_buy = {}
var stripe_pk = "";

function validate(what, text) {
  if (what == 'alias') {
    var re = /^[a-zA-Z0-9 ]{1,25}$/;
  } else if (what == 'smsnumber') {
    var re = /^\+[0-9]{11,11}$/;
  } else if (what == 'email') {
    var re = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([,.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/;
  } else if (what == 'greenzone') {
    var re = /^ *$|^[0-9]+\.[0-9]+,[0-9]+\.[0-9]+,[0-9]+\.[0-9]+,[0-9]+\.[0-9]+$/;
  }

  return re.test(text);
}

function HandleAbocostResponse(data) {
    var ordered = Object.keys(data).sort().reduce(
      (obj, key) => { 
        obj[key] = data[key]; 
        return obj;
      }, 
      {}
    );

    counter = 0;
    total_amount = 0;
    charge_data = '';
    abo_table = '<table class="table is-bordered is-fullwidth" >';
    abo_table += '<tr><th class="is-2">Alias</th><th>verl&auml;ngern bis</th><th class="has-text-right">Betrag</th></tr>';
    jQuery.each(ordered, function (index, val) {
        counter += 1;
        abo_table += '<tr><td>' + val[3] + '</td><td>' + moment(val[2], 'DD.MM.YYYY').add(val[0], 'years').format('DD.MM.YYYY') + '</td><td class="has-text-right">' + (val[1] / 100).toFixed(2) + '</td></tr>';
        total_amount += (val[1] / 100);
        if (charge_data == '') {
          charge_data = index + ":" + val[0] + ":" + val[1];
        } else {
          charge_data += "," + index + ":" + val[0] + ":" + val[1];
        }
    });
    abo_table += '<tr><td>Total CHF</td><td></td><td class="has-text-right">' + (total_amount).toFixed(2) + '</td></tr>';
    abo_table += "</table>";
    if (counter > 0) {
      $("#abos_verlaengern").html(abo_table);
      $("#charge_data").html(charge_data);
      $("#cart").addClass("is-active");
    }
}

$(document).ready(function () {
  abos_to_buy = {};
  $(".show-modal").click(function () {
    $("#alias_exclamation").hide();
    $("#smsnumber_exclamation").hide();
    $("#email_exclamation").hide();
    $("#greenzone_exclamation").hide();

    var alias = $(this).prev().html();

    var deveui = $(this).prev().attr('id').replace("alias_", "");
    $('#deveui').html(deveui);
    var smsalarmactive = $('#smsalarmactive_'+deveui).html();
    var smsnumber = $('#smsnumber_'+deveui).html();
    var emailalarmactive = $('#emailalarmactive_'+deveui).html();
    var email = $('#email_'+deveui).html();
    var greenzone = $('#greenzone_'+deveui).html();

    $("#alias").val(alias);

    if (smsalarmactive == "1") {
      $('#smscheckbox').prop('checked', true);
    } else {
      $('#smscheckbox').prop('checked', false);
    }
    $("#smsnumber").val(smsnumber);

    if (emailalarmactive == "1") {
      $('#emailcheckbox').prop('checked', true);
    } else {
      $('#emailcheckbox').prop('checked', false);
    }
    $("#email").val(email);
    $("#greenzone").val(greenzone);

    $("#modal").addClass("is-active");
  });

  $("#cart-close").click(function () {
    $("#cart").removeClass("is-active");
  });

  $("#payment_notifier_close").click(function () {
    $("#payment_notifier").removeClass("is-active");
    location.reload(true);
  });

  $(".abo_plus").click(function () {
    var deveui = $(this).prev().attr('id').replace("abo_add_years_", "");
    el = $(this).parent().find(".abo_add_years");
    el_text = $(this).parent().parent().find(".abo_add_years_text");
    counter = Number(el.html());
    if (counter < 3) {
      counter = counter + 1;
      if (deveui in abos_to_buy) {
        abos_to_buy[deveui] += 1;
      } else {
        abos_to_buy[deveui] = 1;
      }
      el.html(counter);
      if (counter == 1) {
        el_text.html("+" + counter + " Jahr");
      } else {
        el_text.html("+" + counter + " Jahre");
      }
    }
  });

  $(".abo_minus").click(function () {
    var deveui = $(this).prev().attr('id').replace("abo_", "");
    el = $(this).parent().find(".abo_add_years");
    el_text = $(this).parent().parent().find(".abo_add_years_text");
    counter = Number(el.html());
    if (counter > 0) {
      counter = counter - 1;
      el.html(counter);
      if (deveui in abos_to_buy) {
        abos_to_buy[deveui] -= 1;
        if (abos_to_buy[deveui] == 0) {
          delete abos_to_buy[deveui];
        }
      } 
      if (counter == 0) {
        el_text.html("&nbsp;");
      } else if (counter == 1) {
        el_text.html("+" + counter + " Jahr");
      } else {
        el_text.html("+" + counter + " Jahre");
      }
    }
  });

  function add_years(dt, n) {
    return new Date(dt.setFullYear(dt.getFullYear() + n));
  }

  $(".abo_pay").click(function () {
    if (Object.keys(abos_to_buy).length < 1) {
       return;
    }

    $.ajax({
      url: "abocost",
      type: "POST", //send it through post method
      dataType: "json",
      data: JSON.stringify(abos_to_buy),
      success: function(response) {
        if (stripe_pk == "") {
          stripe_pk = response['stripe_pk'];
          loadStripeLibrary();
        }
        HandleAbocostResponse(response['data']);
      },
      error: function(xhr) {
      }
    });

  });

  $("#modal-close").click(function () {
    $("#modal").removeClass("is-active");
  });

  $("#modal-save").click(function () {
    var smsalarmactive = "0";
    if ($('#smscheckbox').prop('checked')) {
      smsalarmactive = "1";
    }
    var emailalarmactive = "0";
    if ($('#emailcheckbox').prop('checked')) {
      emailalarmactive = "1";
    }

    // Validation Code
    var is_valid = true;
    if (!validate('alias', $('#alias').val())) {
      $('#alias_errormsg').html('Ung&uuml;ltige Bezeichnung; erlaubte Zeichen A-Z, 0-9 und Leerschlag');
      $("#alias").addClass("is-danger");
      $("#alias_exclamation").show();
      is_valid = false;
    } else {
      $('#alias_errormsg').html('');
      $("#alias").removeClass("is-danger");
      $("#alias_exclamation").hide();
    }

    if (!validate('smsnumber',$('#smsnumber').val())) {
       $('#smsnumber_errormsg').html('Beispiel einer g&uuml;ltigen SMS Nummer: +41761234567');
       $("#smsnumber").addClass("is-danger");
       $("#smsnumber_exclamation").show();
       is_valid = false;
    } else {
       $('#smsnumber_errormsg').html('');
       $("#smsnumber").removeClass("is-danger");
       $("#smsnumber_exclamation").hide();
    }

    if (!validate('email',$('#email').val())) {
       $('#email_errormsg').html('Beispiel einer g&uuml;ltigen E-Mail Adresse: max.mustermann@example.com');
       $("#email").addClass("is-danger");
       $("#email_exclamation").show();
       is_valid = false;
    } else {
       $('#email_errormsg').html('');
       $("#email").removeClass("is-danger");
       $("#email_exclamation").hide();
    }

    if (!validate('greenzone',$('#greenzone').val())) {
       $('#greenzone_errormsg').html('Eingabe: lat_min,lon_min,lat_max,lon_max oder aber leeres Feld');
       $("#greenzone").addClass("is-danger");
       $("#greenzone_exclamation").show();
       is_valid = false;
    } else {
       $('#greenzone_errormsg').html('');
       $("#greenzone").removeClass("is-danger");
       $("#greenzone_exclamation").hide();
    }

    if (!(is_valid)) {
      return;
    }

    $.ajax({
      url: "save_tracker_settings",
      type: "get", //send it through get method
      dataType: "json",
      data: {
        deveui: $('#deveui').html(),
        alias: $('#alias').val(),
        smsnumber: $("#smsnumber").val(),
        smsalarmactive: smsalarmactive,
        email: $("#email").val(),
        emailalarmactive: emailalarmactive,
        greenzone: $("#greenzone").val()

      },
      success: function (response) {
        if (response.rc == 0) {
           $('#alias_'+$('#deveui').html()).html($('#alias').val());
           var smsalarmactive = "0";
           if ($('#smscheckbox').prop('checked')) {
             smsalarmactive = "1";
           }
           $('#smsalarmactive_'+$('#deveui').html()).html(smsalarmactive);
           $('#smsnumber_'+$('#deveui').html()).html($('#smsnumber').val());
           var emailalarmactive = "0";
           if ($('#emailcheckbox').prop('checked')) {
             emailalarmactive = "1";
           }
           $('#emailalarmactive_'+$('#deveui').html()).html(emailalarmactive);
           $('#email_'+$('#deveui').html()).html($('#email').val());
           $('#greenzone_'+$('#deveui').html()).html($('#greenzone').val());
        }
      },
      error: function (xhr) {
        //Do Something to handle error
      }
    });

    $("#modal").removeClass("is-active");
  });

});

function loadStripeLibrary() {
  $.ajax({
    url: "https://js.stripe.com/v3/",
    dataType: "script",
    async: false,           // <-- This is the key
    success: function () {
      // all good...
      SetupStripe();
    },
    error: function () {
      throw new Error("Could not load script " + script);
    }
  });
}

function SetupStripe() {
  // Set your publishable key: remember to change this to your live publishable key in production
  // See your keys here: https://dashboard.stripe.com/account/apikeys
  stripe = Stripe(stripe_pk);
  elements = stripe.elements({ locale: "de" });

  // Set up Stripe.js and Elements to use in checkout form
  style = {
    base: {
      color: "#32325d",
    }
  };

  card = elements.create("card", { style: style });
  card.mount("#card-element");
  $("#card-errors-article").hide();

  card.addEventListener('change', ({ error }) => {
    if (error) {
      $("#card-errors").text(error.message);
      $("#card-errors-article").show();
    } else {
      $("#card-errors").text("");
      $("#card-errors-article").hide();
    }
  });
}

function ConfirmPayment(clientSecret) {
  stripe.confirmCardPayment(clientSecret, {
    payment_method: {
      card: card,
      billing_details: {
        name: '{{ .UserName }}'
      }
    }
  }).then(function (result) {
    if (result.error) {
      // Show error to your customer (e.g., insufficient funds)
      $('#card-errors').text(result.error.message);
      $('#card-errors-article').show();
      //Do Something to handle error
      EndPaymentProgress();
    } else {
      // The payment has been processed!
      if (result.paymentIntent.status === 'succeeded') {
        // Show a success message to your customer
        // There's a risk of the customer closing the window before callback
        // execution. Set up a webhook or plugin to listen for the
        // payment_intent.succeeded event that handles any business critical
        // post-payment actions.
        $('#card-errors').text("");
        $('#card-errors-article').hide();
        $("#cart").removeClass("is-active");
        EndPaymentProgress();
        $('#payment_notifier').addClass('is-active');
      }
    }
  });
}

function StartPaymentProgress() {
  $("#cart-pay").attr("disabled", true).addClass("is-loading");
  $("#cart-close").attr("disabled", true);
}

function EndPaymentProgress() {
  $("#cart-pay").attr("disabled", false).removeClass("is-loading");
  $("#cart-close").attr("disabled", false);
}

function PayMe() {
  $.ajax({
    url: "getstripepaymentintent",
    type: "get", //send it through get method
    dataType: "json",
    data: {
      charge_data: $("#charge_data").html()
    },
    success: function (response) {
      if (response.rc == 0) {
        ConfirmPayment(response.stripeclientsecret);
      }
    },
    error: function (xhr) {
      //Do Something to handle error
      EndPaymentProgress();
    }
  });
}

$('#cart-pay').on('click', function (ev) {
  StartPaymentProgress();
  PayMe();
});

// draw all maps
var woBischIcon = L.icon({
  iconUrl: '/static/images/marker.png',
  iconSize: [64, 64],
  iconAnchor: [32, 64]
});

var maps = [];
$(document).ready(function () {
  $(".tracker").each(function (index) {

    deveui = $(this).find("div").first().attr("id");
    lat = $(this).find("#lat").html();
    lon = $(this).find("#lon").html();
    var map = new L.Map('map_' + deveui, {
      crs: L.CRS.EPSG3857,
      zoomControl: false
    });
    map.dragging.disable();
    map.touchZoom.disable();
    map.doubleClickZoom.disable();
    map.scrollWheelZoom.disable();
    map.boxZoom.disable();
    map.keyboard.disable();
    if (map.tap) map.tap.disable();
    var url = 'https://wmts20.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg';
    var tilelayer = new L.tileLayer(url);
    map.addLayer(tilelayer);
    map.attributionControl.setPrefix('Source: Swiss Federal Office of Topography')
    map.setView(L.latLng(lat, lon), 10);

    var marker = L.marker([lat, lon], { icon: woBischIcon }).addTo(map);

    maps.push(map);

  });
});
