'use strict';
var edit = edit || {};

edit.init = function() {
  var DOWNLOAD_NAME = 'index.maildigit';
  // Apply contenteditable attributes on text elements
  $('p,h1,h2,h3,h4,h5,h6,a,li,ul').attr('contenteditable', 'true');

  // Add Save/Load menu
  $('body').prepend(
    "<div class='editor' style='position:fixed; top: 250px; z-index: 10000;'><button class='btn btn-default editersauve'>Sauvegarder les modifications</button> \
                      <!--<button class='btn btn-default editercharge'>Charger des modifications</button>--> \
                      <input  style='display:none;' type='file' class='chargehisto'/></div>"
  );

  // Add button to upload file below each image
  $('img').each(function(i) {
    //logger.info($(this).attr('src'));
    $(this).attr('src', $(this).attr('src'));
    $(this).attr('H', $(this).css('height'));
    $(this).attr('L', $(this).attr('width'));
    $(this)
      .closest('div')
      .append("<input type='file' class='imageLoader'/>");
  });

  // Replace old image with the new uploaded image in base64
  $('.imageLoader').on('change', function(e) {
    var imgEl = $(this)
      .closest('div')
      .find('img');
    // Get img tree like /images/equipe or /images/
    var tree = imgEl[0].src.split(window.location.origin)[1];
    // This is needed because if we change two times an image at the same place
    // first time we replaced it the src will be in base64
    // then we need to find the computed src which is stored in dataset.tree
    if (!tree) tree = imgEl[0].dataset.tree;
    tree = tree.substr(0, tree.lastIndexOf('/') + 1);
    if ($(this)[0].files.length === 1) {
      var fileName = $(this)[0].files[0].name;
      fileName = fileName.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); // remove accents
      fileName = fileName.replace(/\s+/g, '_'); // remove spaces
      var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
      // Add fileName and tree in data attributes
      imgEl[0].dataset.fileName = fileName;
      imgEl[0].dataset.tree = tree + fileName;
      logger.info(imgEl[0].dataset.tree);
      // logger.info(imgEl);

      if (ext === 'gif' || ext === 'png' || ext === 'jpeg' || ext === 'jpg') {
        var reader = new FileReader();
        reader.onload = function(e) {
          imgEl.attr('src', e.target.result);
        };
        reader.readAsDataURL($(this)[0].files[0]);
      }
    }
  });

  $('button.editercharge').on('click', function() {
    $(this)
      .closest('div')
      .find('.chargehisto')
      .trigger('click');
  });
  $('.chargehisto').on('change', function(e) {
    if ($(this)[0].files !== undefined) {
      //charge un dom avec les info et recupere tous les editables et les changes dans le dom d'origine pour mettre à jour
      // a developper en prod recupere fichier
      var ext = $(this)[0]
        .files[0]['name'].substring(
          $(this)[0].files[0]['name'].lastIndexOf('.') + 1
        )
        .toLowerCase();
      if ($(this)[0].files && $(this)[0].files[0] && ext == 'maildigit')
        var reader = new FileReader();
      reader.onload = function(e) {
        $('body').html(e.target.result);
      };
      reader.readAsText($(this)[0].files[0]);
    }
  });

  $('button.editersauve').on('click', function() {
    //nettoie editeur
    //$('p,h1,h2,h3,h4,a').removeAttr('contenteditable');
    //$('button.editersauve, p.editinfo').remove();
    //recupere body
    var a = window.document.createElement('a');
    a.href = window.URL.createObjectURL(
      new Blob([$('body').html()], {
        type: 'text/csv;charset=utf-8;'
      })
    );
    a.download = DOWNLOAD_NAME;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  });
};

$(document).ready(function() {
  if (window.location.href.indexOf('#editer_') > -1) edit.init();
});
