const quill = {
  construct: function(element) {
    function loop() {
      let html = $(element).find('.ql-editor').html();
      let n;
      
      if (element.attr('data-name')) {
        n = element.attr('data-name');
      } else {
        n = element.attr('name');
        element.attr('data-name', n).removeAttr('name');
      }

      let i = element.find('input[name="' + n + '"]');
      if (i.length == 0) {
        i = $(`<input type="text" class="d-none" name="${n}">`);
        element.append(i);
      }
      
      i.val('');
      i.val(html);
      $(i).trigger('change');
      return n;
    }

    var customHrHandler = function(){
      // get the position of the cursor
      var range = this.quill.getSelection();
      if (range) {
        // insert the <hr> where the cursor is
        this.quill.insertEmbed(range.index,"hr","null");
        this.quill.setSelection(range.index + 1, 0);
      }
    }

    let element_fix = element[0];

    var Embed = Quill.import('blots/block/embed');
    class Hr extends Embed {
      static create(value) {
        let node = super.create(value);
        node.setAttribute('style', "height:0px; margin-top:30px; margin-bottom:30px; position: relative;");
        return node;
      }
    }

    Hr.blotName = 'hr';
    Hr.className = 'my-hr';
    Hr.tagName = 'hr';

    Quill.register({
      'formats/hr': Hr
    });

    let ed = new Quill(element_fix, {
      modules: { 
        toolbar: {
          container: [
            [
              { font: [] }, 
              { size: [] }
            ], 
            ["bold", "italic", "underline", "strike"], 
            [
              { color: [] }, 
              { background: [] }
            ], 
            [
              { script: "super" }, 
              { script: "sub" }
            ], 
            [
              { list: "ordered" }, 
              { list: "bullet" }, 
              { indent: "-1" }, 
              { indent: "+1" }
            ], 
            ["direction", { align: [] }], 
            ["link", "image", "video"], 
            ["clean"]
          ]
        }
      },
      placeholder: "Digite aqui...",
      theme: "snow"
    });

    const hrButton = new QuillToolbarButton({
      icon: `<i class="fas fa-horizontal-rule"></i>`
    })
     
    // hrButton.onClick = function(q) {
    //   const { index, length } = q.selection.savedRange
    //   const selectedText = q.getText(index, length)
    //   const newText = selectedText.toUpperCase()
    //   q.deleteText(index, length)
    //   q.insertText(index, newText)
    //   q.setSelection(index, newText.length)
    // }

    hrButton.onClick = customHrHandler;
    hrButton.attach(ed)

    ed.on('editor-change', function(delta, oldDelta, source) {
      loop();
    });

    loop();
    
    return ed;
  }

}

const core = {
  quill: quill,

  current_modal: null,

  load_modal: function (url, options) {
    if (options === undefined) options = {};
    if (options.method === undefined) options.method = 'get';
    if (options.data === undefined) options.data = null;

    $.ajax({
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
      method: options.method,
      url: url,
      data: options.data,
      success: function (res) {
        let $el = $(res).appendTo('body');
        let $el_modal = $($el).find('.modal');
        
        let $modal = new bootstrap.Modal($el_modal[0]);
        $modal.show();

        $el_modal.on('hidden.bs.modal', event => {
          core.current_modal = null;
          if (options.onClose) {
            options.onClose.call();
          }
          $el.remove();
        });

        core.current_modal = $modal;
        $el.trigger('ready');
      }
    });
  },

  /*
  * options: {
    title: titulo da mensagem de sucesso ou erro
    msg: {
      success: mensagem de sucesso
      fail: mensagem de erro
    }
    onSuccess: callback sucesso
    onFail: callback erro
    submitButton: botao de submit
  }
  *
  */
  ajaxForm: function(element, options) {    
    if (options === undefined) options = {};
    if (options.title === undefined) options.title = '';
    if (options.msg === undefined) options.msg = {};
    if (options.msg.success === undefined) options.msg.success = 'Formulário enviado com sucesso';
    if (options.msg.fail === undefined) options.msg.fail = 'Erro ao enviar formulário';

    let form = $(element);
    let btn_form = form.find('button[type="submit"]');

    options.succesCallback = function (result) {
      if (result.status == 'success') {
        if (options.onSuccess === undefined) {
          Swal.fire(options.title, options.msg.success, 'success');
        } else {
          options.onSuccess.call(form, result);
        }
      } else {
        if (options.onFail === undefined) {
          options.onFail.call(form, result);
        } else {
          let error = result;
          if (result.message !== undefined) error = result.message;
          
          Swal.fire(options.msg.fail, error, 'error');
        }
      }
    }

    if (options.onFail === undefined) {
      options.onFail = function (result) {
        let error = result;
        if (result.message !== undefined) error = result.message;

        Swal.fire(options.msg.fail, error, 'error');
      }
    }

    if (options.submitButton !== undefined) btn_form = options.submitButton;
    
    form.ajaxForm({
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
      beforeSend: function() {
        btn_form.attr('disabled', 'disabled');
      },
      success: function(res) {
        btn_form.removeAttr('disabled');
        
        options.succesCallback.call(form, res)
      },
      error: function(res) {
        btn_form.removeAttr('disabled');
        
        options.onFail.call(form, res)
      }
    });
  },

  ajax: function(btn, url, method, data, options) {    
    if (btn === undefined) {
      console.error('Botão não informado');
      return false;
    }

    if (url === undefined) {
      console.error('URL não informada');
      return false;
    }

    if (method === undefined) {
      console.error('Método não informado');
      return false;
    }

    if (data === undefined) data = {};
    if (options === undefined) options = {};
    if (options.title === undefined) options.title = '';
    if (options.msg === undefined) options.msg = {};
    if (options.msg.success === undefined) options.msg.success = 'Requisição enviada com sucesso';
    if (options.msg.fail === undefined) options.msg.fail = 'Erro ao enviar requisição';

    btn.attr('disabled', true);

    options.succesCallback = function (result) {
      if (result.status == 'success') {
        if (options.onSuccess === undefined) {
          Swal.fire(options.title, options.msg.success, 'success');
        } else {
          options.onSuccess.call(null, result);
        }
      } else {
        if (options.onFail === undefined) {
          options.onFail.call(null, result);
        } else {
          let error = result;
          if (result.message !== undefined) error = result.message;
          
          Swal.fire(options.msg.fail, error, 'error');
        }
      }
    }

    if (options.onFail === undefined) {
      options.onFail = function (result) {
        let error = result;
        if (result.message !== undefined) error = result.message;

        Swal.fire(options.msg.fail, error, 'error');
      }
    }

    $.ajax({
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
      url: url,
      method: method,
      data: data,
      success: function (result) {
        btn.removeAttr('disabled');
        options.succesCallback.call(null, result)
      },
      fail: function (result) {
        btn.removeAttr('disabled');
        options.onFail.call(null, result)
      }
    });
  },

  uniqid: function(prefix = "", random = false) {
    const sec = Date.now() * 1000 + Math.random() * 1000;
    const id = sec.toString(16).replace(/\./g, "").padEnd(14, "0");
    return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}`:""}`;
  }
}; 