function setText(textarea, text, inicio, fim, _in) {
  textarea.value = text;
  textarea.selectionStart = inicio + _in.length;
  textarea.selectionEnd = fim + _in.length;
  textarea.focus();
}

$(function () {
  function editText(textarea, _in, _out) {
    let inicio = textarea.selectionStart;
    let fim = textarea.selectionEnd;
    let valor = textarea.value;

    switch (inicio === fim) {
      case true:
        setText(
          textarea,
          valor.slice(0, inicio) + _in + "texto aqui" + _out + valor.slice(fim),
          inicio,
          fim,
          _in,
        );
        break;
      default:
        setText(
          textarea,
          valor.slice(0, inicio) +
            _in +
            valor.slice(inicio, fim) +
            _out +
            valor.slice(fim),
          inicio,
          fim,
          _in,
        );

        break;
    }
  }
  let txt = true;
  $("#text-write ul span").on("click", function () {
    let list = [
      { start: "# ", end: "" },
      { start: "## ", end: "" },
      { start: "### ", end: "" },
      { start: "**", end: "**" },
      { start: "_", end: "_" },
      {
        addImg: function () {
          editText($("#edit")[0], "[[img]{},'", "',size,100,100]");
        },
      }, // especial
      { start: "- ", end: "" },
      { start: "> ", end: "" },
    ];
    let md = list[$(this).index()];

    try {
      md.addImg ? md.addImg() : editText($("#edit")[0], md.start, md.end);
    } catch {
      switch (txt) {
        case true:
          $(".txtarea").hide();
          $(".txtmark").show();
          $(".txtmark div").html(marked.parse($("#edit")[0].value));

          txt = false;
          break;
        default:
          $(".txtarea").show();
          $(".txtmark").hide();
          txt = true;
          break;
      }
    }
  });
});
