const config = {
    securityLevel:'loose',
      theme: 'base',
      startOnLoad: true,
      };
     mermaid.initialize(config);

    function editNode(config, id) {
      var merm = document.getElementById("mermaid-chart");
     // var graphid = merm.outerText.split("\n"); 

     var graphid = [];

     document.querySelectorAll('.nodeLabel').forEach((label) => {
            graphid.push(label.textContent);
     });
      
      
      graphid = split_nodes(graphid);

      const without_quotes = graphid[id].substring(
        graphid[id].indexOf("`") + 1,
        graphid[id].lastIndexOf("`"));

        if (without_quotes !== '') {
            graphid[id] = without_quotes;
        }
      
      (async () => {
        const { value: newvalue } = await Swal.fire({
        title: "Πληκτρολόγησε μια ή περισσότερες λέξεις (όχι πολλές!)",
        input: "text",
        inputPlaceholder: "Πληκτρολόγησέ εδώ...",
        inputAttributes: {
          "aria-label": "Πληκτρολόγησέ εδώ..."
        },
        inputValue: graphid[id],
        showCancelButton: false,
        showClass:{ popup: 'swal2-show'},
        hideClass:{ popup: 'swal2-hide'},
      })
    
      if (newvalue !== null && newvalue !== undefined && newvalue.trim() !== "") {
        graphid[id] = preparestr(newvalue);     
     } else {
       graphid[id] = '_______';
     }
   
      merm.removeAttribute('data-processed');
      merm.innerHTML = 
      `
      flowchart TD;
        A((ΤΟ <br/>ΣΩΜΑ ΜΟΥ)) -- έχει --> B((5<br/>αισθήσεις))
            B--->|είναι| B1[` + graphid[2] + `]
            B--->|είναι| B2[όραση]
            B--->|είναι| B3[` + graphid[4] + `]
            B--->|είναι| B4[γεύση]
            B--->|είναι| B5[` + graphid[6] + `]
        A-- προστατευω<br/>όταν --> C((λέω ΟΧΙ))
            C-->|όπως| C1[` + graphid[8] + `]
            C-->|όπως| C2[` + graphid[9] + `]
        A-- φροντίζω<br/>όταν --> D((ασκούμαι))
            D-->|καθημερινά| D1[` + graphid[11] + `]
            D-->|λιγότερο συχνά| D3[` + graphid[12] + `]
        A-- φροντίζω<br/>όταν --> E((τρέφομαι<br/>σωστά))
            E-->|σημαίνει| E1[` + graphid[14] + `]
            E-->|σημαίνει| E2[` + graphid[15] + `]
            E-->|σημαίνει| E3[` + graphid[16] + `]
        A-- φροντίζω<br/>όταν --> F((` + graphid[17] + `))
            F-->|τουλάχιστον| F1[9-12 ωρες]
        

            click B1 "javascript:editNode(config, 2)"
            click B3 "javascript:editNode(config, 4)"
            click B5 "javascript:editNode(config, 6)"
            click C1 "javascript:editNode(config, 8)"
            click C2 "javascript:editNode(config, 9)"
            click D1 "javascript:editNode(config, 11)"
            click D3 "javascript:editNode(config, 12)"
            click E1 "javascript:editNode(config, 14)"
            click E2 "javascript:editNode(config, 15)"
            click E3 "javascript:editNode(config, 16)"
            click F "javascript:editNode(config, 17)"
              
        style A fill:#ed6,stroke:#333,stroke-width:2px;
        style B fill:#ed6,stroke:#333,stroke-width:2px;
        style C fill:#ed6,stroke:#333,stroke-width:2px;
        style D fill:#ed6,stroke:#333,stroke-width:2px;
        style E fill:#ed6,stroke:#333,stroke-width:2px;
        style F fill:#ed6,stroke:#333,stroke-width:2px;

`; 

      mermaid.init(config, ".mermaid");
})();

};  

  function preparestr(s){

   var specialChars = "@\`'\"();~<>+=-[]\\/{}|";

    for (var i = 0; i < specialChars.length; i++) {
      s = s.replace(new RegExp("\\" + specialChars[i], "gi"), "");
    }

    return s.trim();
  }
              


  function split_nodes(graphid) {
    for (var i=0; i < graphid.length; i++) {
         if (i <= graphid.length-2 && (graphid[i] === '' && graphid[i+1] !== '' && graphid[i+2]==='')) {
              graphid[i+1] = '"`' + graphid[i+1] +'`"'; 
          }
    }
    graphid = graphid.filter(a => a!="");

    return graphid;
  }

 function saveDiagramAsImage() {
  var svgElement = document.querySelector('#mermaid-chart svg');

  var svgRect = svgElement.getBoundingClientRect();
  var scaleFactor = window.devicePixelRatio || 1;

  var canvas = document.createElement('canvas');
  
  canvas.width = (svgRect.width + svgRect.width * 0.4) * scaleFactor;
  canvas.height = (svgRect.height + svgRect.height * 0.4) * scaleFactor;

  var ctx = canvas.getContext('2d');

  ctx.scale(scaleFactor, scaleFactor);

  var svgData = new XMLSerializer().serializeToString(svgElement);
  var svgURL = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgData);

  var img = new Image();
  img.onload = function() {
      ctx.drawImage(img, 0, 0, svgRect.width + svgRect.width * 0.4, svgRect.height + svgRect.height * 0.4);

      var link = document.createElement('a');
      link.download = 'Το σώμα μου.png';
      link.href = canvas.toDataURL('image/png');
      link.click();
  };
  img.src = svgURL;
}

// button event listener 
document.getElementById('saveButton').addEventListener('click', saveDiagramAsImage);
