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

edit.article = function() {
  // Add remove an article
  $('section.filterlist .card-group .card').append(`
    <p>
      <button class='btn btn-primary deleteArticle' title="Attention supprime l'article">
         <i class="fas fa-trash"></i>
      </button>
      <button class='btn btn-primary hideArticle' title="Cache l'article sans le supprimer">
         <i class="fas fa-eye-slash"></i>
      </button>
      <button class='btn btn-primary editArticle' title="Editer l'article">
         <i class="fas fa-edit" ></i>
      </button>
      <button class='btn btn-primary cloneArticle' title="Clone un article et l'ajoute">
         <i class="fas fa-clone" ></i>
      </button>
    </p>
    `);
  // Add element data for each modal article
  $('.dataarticle').each(function(i, ele) {
    $(this).prepend(`
      <p title="Liste des tag utilisés pour filtrer cette article">
        <b>cardtag:</b><span class='data-cardtag' contenteditable="true" >${$(this).attr('data-cardtag')}</span>
      </p>
      <p title="Titre de chaque carte">
        <b>cardtitle:</b><span class='data-cardtitle' contenteditable="true" >${$(this).attr('data-cardtitle')}</span>
      </p>
      <p title="Sous-titre de chaque carte">
        <b>cardtext:</b><span class='data-cardtext' contenteditable="true" >${$(this).attr('data-cardtext')}</span>
      </p>
      <p title="Texte en petit de charte carte">
        <b>cardsmalltext:</b><span class='data-cardsmalltext' contenteditable="true" >${$(this).attr('data-cardsmalltext')}</span>
      </p>
      `)
  })
  $('.card').attr('data-toggle', 'none');
  $('button.deleteArticle').on('click', function(e) {
    if(confirm("Attention, l'article va être définitivement supprimé, êtes-vous sur?")) {
      $(this).closest('[data-uuid]').attr('data-update', 'delete');
      $(this).closest('[data-uuid]').hide();
    }
  })
  $('button.hideArticle').on('click', function(e) {
    if($(this).closest('[data-uuid]').attr('data-update') != 'hide') {
      $(this).closest('[data-uuid]').attr('data-update', 'hide');
      $(this).closest('[data-uuid]').css('background-color', 'rgb(0,0,0,0.2)');
    } else {
      $(this).closest('[data-uuid]').attr('data-update', '');
      $(this).closest('[data-uuid]').css('background-color', 'rgb(0,0,0,0)');
    }
  })
  $('button.editArticle').on('click', function(e) {
    $(this).closest('[data-uuid]').attr('data-update', 'update');
    $(this).closest('.card').attr('data-toggle', 'modal');
  })
  $('button.cloneArticle').on('click', function(e) {
    //alert('todo from template ')
    var origin = $(this).closest('[data-uuid]')
    var originuuid = origin.attr('data-uuid')
    logger.info(originuuid)
  })

}

edit.image = function() {
  // Add button to upload file below each image
  if($('input.imageLoader').length == 0) {
    $('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'));
      const alt = $(this).attr('alt')
      $(this)
        .closest("[contenteditable='true']")
        .append(`<p class="editortag">alt=<span class="alt" contenteditable='true'>${alt}</span><br><input type='file' class='imageLoader'/>`);
    });
  };
  // Replace old image with the new uploaded image in base64
  $('body').on('change', '.imageLoader', function(e) {
    var imgEl = $(this)
      .closest("[contenteditable='true']")
      .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]);
      }
    }
  });
}

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');
  edit.article();
  edit.image();
  // Add Save/Load menu
  $('body').prepend(
    `<div class='editor' style='position:fixed; bottom: 5px; z-index: 1000000;'>
      <button class='btn btn-primary editersauve' title="sauvegarde les modifications">
        <i class="fas fa-save"></i>
      </button>
      <button class='btn btn-primary editercharge' title="charge une sauvegarde">
        <i class="fas fa-file-import"></i>
      </button>
      <input  style='display:none;' type='file' class='chargehisto'/>
      .
      <button class='btn btn-primary addheader2' title='Ajoute un entete'>
        <i class="fas fa-heading">2</i>
      </button>
      <button class='btn btn-primary addparagraphe' title='Ajoute un paragraphe à la suite'>
        <i class="fas fa-paragraph"></i>
      </button>
      <button class='btn btn-primary addlist' title='Ajoute une liste à la suite'>
        <i class="fas fa-list"></i>
      </button>
      <button class='btn btn-primary addimage' title='Ajoute une image'>
        <i class="fas fa-image"></i>
      </button>
      <button class='btn btn-primary addhyperlien' title='Ajoute un lien hypertexte'>
        <i class="fas fa-link"></i>
      </button>
      <button class='btn btn-primary eraseselection' title='Supprime la selection en cours'>
        <i class="fas fa-eraser"></i>
      </button>
      .
      <button class='btn btn-primary aligncenter' title='Centre le texte du curseur'>
        <i class="fas fa-align-center"></i>
      </button>
      <button class='btn btn-primary alignjustify' title='Justifie le texte du curseur'>
        <i class="fas fa-align-justify"></i>
      </button>
      <button class='btn btn-primary alignright' title='cale à droite'>
        <i class="fas fa-align-right"></i>
      </button>
      <button class='btn btn-primary alignleft' title='cale à gauche'>
        <i class="fas fa-align-left"></i>
      </button>
      .
      <button class='btn btn-dark addBold' title='Mise en gras de la selection'>
        <i class="fas fa-bold"></i>
      </button>
      <button class='btn btn-primary color' data-color='text-primary' title='Change la couleur de texte'>
        <i class="fas fa-palette"></i>
      </button>
      <button class='btn btn-secondary color' data-color='text-secondary' title='change la couleur de texte'>
        <i class="fas fa-palette"></i>
      </button>
      <button class='btn btn-primary removeformat' title='Supprime le format de la selection'>
        <i class="fas icon-action-undo"></i>
      </button>
    </div>`
  );
  $('body').on('focus', 'p,h1,h2,h3,h4,h5,h6,a,li,ul', function(e) {
    $('.selectionencours').removeClass('selectionencours')
    $(this).addClass('selectionencours')
  });
  $('button.addheader2').on('click', function() {
    $('<h2 contenteditable="true">x</h2>').insertAfter('.selectionencours')
    $('.selectionencours').removeClass('selectionencours')
  })
  $('button.addparagraphe').on('click', function() {
    $('<p contenteditable="true">x</p>').insertAfter('.selectionencours')
    $('.selectionencours').removeClass('selectionencours')
  })
  $('button.addlist').on('click', function() {
    $('<ul contenteditable="true"><li contenteditable="true">x</li></ul>').insertAfter('.selectionencours')
    $('.selectionencours').removeClass('selectionencours')
  })
  $('button.addimage').on('click', function() {
    $(`
      <p>
        <img src="" alt="" class="img-fluid"><br>
        alt=<span class="alt" contenteditable='true'></span><br>
        <input type="file" class="imageLoader"/>
      </p>
      `).insertAfter('.selectionencours')
    $('.selectionencours').removeClass('selectionencours')
  })

  $('button.eraseselection').on('click', function() {
    $('.selectionencours').remove()
  })
  $('button.aligncenter').on('click', function() {
    $('.selectionencours').removeClass('text-justify').removeClass('text-right').removeClass('text-left');
    $('.selectionencours').addClass('text-center')
  })
  $('button.alignjustify').on('click', function() {
    $('.selectionencours').removeClass('text-center').removeClass('text-right').removeClass('text-left');
    $('.selectionencours').addClass('text-justify')
  })
  $('button.alignright').on('click', function() {
    $('.selectionencours').removeClass('text-justify').removeClass('text-center').removeClass('text-left');
    $('.selectionencours').addClass('text-right')
  })
  $('button.alignleft').on('click', function() {
    $('.selectionencours').removeClass('text-justify').removeClass('text-right').removeClass('text-center');
    $('.selectionencours').addClass('text-left')
  })
  $('button.removeformat').on('click', function() {
    const txtencours = $('.selectionencours').html().replace(/<[^>]*>/g, '')
    $('.selectionencours').html(txtencours);
  })
  $('button.addBold').on('click', function() {
    const sel = window.getSelection().toString();
    const txtencours = $('.selectionencours').html().replace(sel, `<b>${sel}</b>`)
    $('.selectionencours').html(txtencours);
  });
  $('button.color').on('click', function(e) {
    const colo = $(this).attr('data-color')
    const sel = window.getSelection().toString();
    const txtencours = $('.selectionencours').html().replace(sel, `<span class='${colo}'>${sel}</span>`)
    $('.selectionencours').html(txtencours);
  });

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