export default class PDFOptionsDialog {
   /**
    * Initializes the dialog.
    */
   constructor (containerDivElem) {
      this.containerDivElem = containerDivElem;

      containerDivElem.innerHTML = `
         <dialog id="NETRONIC-VSW-PDFDialog">
            <style>
               #NETRONIC-VSW-PDFDialog .numberInput {
                  width: 50px;
                  text-align: right;
               }
               #NETRONIC-VSW-PDFDialog .textInput {
                  width: 400px;
                  height: 120px;
                  word-break: break-word;
               }
               #NETRONIC-VSW-PDFDialog .buttons {
                  display: flex;
                  justify-content: flex-end;
                  gap: 10px;
               }
            </style>
            <span style="color:darkred;font-style:italic;font-weight:bold;"><i class="fas fa-exclamation-triangle"></i> This dialog is not part of VSW!</span>
            <table>
               <tr>
                  <td>
                     <p>
                        <fieldset>
                           <legend>Printing mode</legend>
                           <input id="printingMode0" type="radio" value="0" name="printingMode"/>
                           <label for="printingMode0">Single</label>
                           <input id="printingMode1" type="radio" value="1" name="printingMode"/>
                           <label for="printingMode1">Cutting</label>
                           <input id="printingMode2" type="radio" value="2" name="printingMode" checked/>
                           <label for="printingMode2">Paging</label>
                        </fieldset>
                     </p>
                     <p>
                        <input type="checkbox" id="CutMarksVisible" disabled/>
                        <label for="CutMarksVisible">Cut marks visible</label>
                     </p>
                     <p id="pageFormats">
                        <label for="PageFormat">Page format:</label>
                        <select id="PageFormat">
                           <option value="A0">DIN A0</option>
                           <option value="A1">DIN A1</option>
                           <option value="A2">DIN A2</option>
                           <option value="A3">DIN A3</option>
                           <option value="A4" selected>DIN A4</option>
                           <option value="Legal">Legal</option>
                           <option value="Letter">Letter</option>
                        </select>
                     </p>
                     <p>
                        <fieldset id="pageOrientations">
                           <legend>Page orientation</legend>
                           <input id="pageOrientation0" type="radio" value="0" name="pageOrientation" checked/>
                           <label for="pageOrientation0">Portrait</label>
                           <input id="pageOrientation1" type="radio" value="1" name="pageOrientation"/>
                           <label for="pageOrientation1">Landscape</label>
                        </fieldset>
                     </p>
                     <p>
                        <fieldset>
                           <legend>Page margins in millimeters</legend>
                           <table>
                              <tr>
                                 <td>Top:</td>
                                 <td>
                                    <input type="number" id="TopPageMargin" min=0 value=10 class="numberInput"/>
                                 </td>
                                 <td>Left:</td>
                                 <td>
                                    <input type="number" id="LeftPageMargin" min=0 value=10 class="numberInput"/>
                                 </td>
                              </tr>
                              <tr>
                                 <td>Bottom:</td>
                                 <td>
                                    <input type="number" id="BottomPageMargin" min=0 value=10 class="numberInput"/>
                                 </td>
                                 <td>Right:</td>
                                 <td>
                                    <input type="number" id="RightPageMargin" min=0 value=10 class="numberInput"/>
                                 </td>
                              </tr>
                           </table>
                        </fieldset>
                     </p>
                     <fieldset id="sizingModes">
                        <legend>Sizing mode</legend>
                        <input id="sizing0" type="radio" value=0 name="sizing" checked/>
                        <label for="sizing0">Maximum page counts</label>
                        <table>
                           <tr>
                              <td style="width:20px"></td>
                              <td>Horizontal:
                                 <input type="number" id="HorizontalPageCountLimit" min=1 value=1 class="numberInput"/>
                              </td>
                              <td>Vertical:
                                 <input type="number" id="VerticalPageCountLimit" min=1 value=1 class="numberInput"/>
                              </td>
                           </tr>
                        </table>
                        <input id="sizing1" type="radio" value=1 name="sizing"/>
                        <label for="sizing1">Scaling</label>
                        <table>
                           <tr>
                              <td style="width:20px"></td>
                              <td>Zoom factor as percentage:
                                 <input type="number" id="ZoomPercentage" min=1 value=100 class="numberInput" disabled/>
                              </td>
                           </tr>
                        </table>
                     </fieldset>
                  </td>
                  <td>
                     <p>
                        <label for="StartDate">Start date</label>
                        <input type="datetime-local" id="StartDate"/>
                     </p>
                     <p>
                        <label for="EndDate">End date</label>
                        <input type="datetime-local" id="EndDate"/>
                     </p>
                     <p>
                        <fieldset>
                           <legend>Text in top page margin</legend>
                           <textarea id="TopText" class="textInput"></textarea>
                           <br/>
                           <input type="checkbox" id="TopTextInHTML"/>
                           <label for="TopTextInHTML">Text above interpreted as HTML</label>
                        </fieldset>
                        <fieldset>
                           <legend>Text in bottom page margin</legend>
                           <textarea id="BottomText" class="textInput"></textarea>
                           <br/>
                           <input type="checkbox" id="BottomTextInHTML"/>
                           <label for="BottomTextInHTML">Text above interpreted as HTML</label>
                        </fieldset>
                     </p>
                     <p>
                        <input type="checkbox" id="BottomTimescale" checked/>
                        <label for="BottomTimescale">Bottom timescale visible</label>
                     </p>
                  </td>
               </tr>
            </table>
            <div class="buttons">
               <button id="Save" autofocus>Save</button>
               <button id="Close">Close</button>
            </div>
         </dialog>
      `;

      this.dialog = containerDivElem.querySelector("#NETRONIC-VSW-PDFDialog");

      containerDivElem.querySelectorAll('input[name="printingMode"]').forEach(elem => {
         elem.addEventListener("change", event => {
            const value = +event.currentTarget.value;
            const isSingle = (value !== 0);
            this.setEnabled(containerDivElem.querySelector("#PageFormat"), isSingle);
            this.setEnabled(containerDivElem.querySelector("#pageOrientations"), isSingle);
            this.setEnabled(containerDivElem.querySelector("#PageFormat"), isSingle);
            this.setEnabled(containerDivElem.querySelector("#sizingModes"), isSingle);
            this.setEnabled(containerDivElem.querySelector("#CutMarksVisible"), value === 1 /*Cutting*/);
         })
      });

      containerDivElem.querySelectorAll('input[name="sizing"]').forEach(elem => {
         elem.addEventListener("change", event => {
            const withPageCountLimits = (+event.currentTarget.value === 0);
            this.setEnabled(containerDivElem.querySelector("#HorizontalPageCountLimit"), withPageCountLimits);
            this.setEnabled(containerDivElem.querySelector("#VerticalPageCountLimit"), withPageCountLimits);
            this.setEnabled(containerDivElem.querySelector("#ZoomPercentage"), !withPageCountLimits);
         })
      });

      containerDivElem.querySelector("#Save").addEventListener("click", () => {
         const sizingMode = containerDivElem.querySelector('input[name="sizing"]:checked').value;
         const topTextInHTML = containerDivElem.querySelector('#TopTextInHTML').checked;
         const bottomTextInHTML = containerDivElem.querySelector('#BottomTextInHTML').checked;
         const topText = containerDivElem.querySelector("#TopText").value;
         const bottomText = containerDivElem.querySelector("#BottomText").value;
         this.options = {
            pageOrientation: +containerDivElem.querySelector('input[name="pageOrientation"]:checked').value,
            printingMode: +containerDivElem.querySelector('input[name="printingMode"]:checked').value,
            pageFormat: containerDivElem.querySelector("#PageFormat").value,
            bottomPageMargin: +containerDivElem.querySelector("#BottomPageMargin").value,
            leftPageMargin: +containerDivElem.querySelector("#LeftPageMargin").value,
            rightPageMargin: +containerDivElem.querySelector("#RightPageMargin").value,
            topPageMargin: +containerDivElem.querySelector("#TopPageMargin").value,
            horPageCountLimit: (sizingMode == "0") ? +containerDivElem.querySelector("#HorizontalPageCountLimit").value : undefined,
            verPageCountLimit: (sizingMode == "0") ? +containerDivElem.querySelector("#VerticalPageCountLimit").value : undefined,
            zoomFactorInPercent: (sizingMode == "1") ? +containerDivElem.querySelector("#ZoomPercentage").value : undefined,
            bottomTimescaleVisible: !!containerDivElem.querySelector("#BottomTimescale").checked,
            cutMarksVisible: !!containerDivElem.querySelector("#CutMarksVisible").checked,
            topText: !topTextInHTML ? topText : undefined,
            bottomText: !bottomTextInHTML ? bottomText : undefined,
            topHTML: topTextInHTML ? topText : undefined,
            bottomHTML: bottomTextInHTML ? bottomText : undefined,
            start: containerDivElem.querySelector("#StartDate").value || undefined,
            end: containerDivElem.querySelector("#EndDate").value || undefined,
         };

         this.dialog.close("ok");
      });

      containerDivElem.querySelector("#Close").addEventListener('click', () => {
         this.dialog.close("cancel");
      });
   }

   setEnabled (elem, newState) {
      if (newState)
         elem.removeAttribute("disabled");
      else
         elem.setAttribute("disabled", "");
   }

   setChecked (groupName, newValue) {
      const selector = `input[name="${groupName}"]`;
      const elems = Array.from(this.containerDivElem.querySelectorAll(selector));
      if (!elems.some(elem => elem.checked = (elem.value === newValue)))
         elems[0].checked = true;
      this.containerDivElem.querySelector(`${selector}:checked`).dispatchEvent(new Event("change"));
   }

   setSelected (selectElemID, newValue) {
      const selector = `#${selectElemID} option`;
      const elems = Array.from(this.containerDivElem.querySelectorAll(selector));
      if (!elems.some(elem => elem.selected = (elem.value === newValue)))
         elems[0].selected = true;
      this.containerDivElem.querySelector(`${selector}:checked`).dispatchEvent(new Event("change"));
   }

   /**
    * Shows the modal dialog with the given PDF options.
    */
   showModal (options) {
      if (options) {
         if (options.pageOrientation != null)
            this.setChecked("pageOrientation", options.pageOrientation.toString());
         if (options.printingMode != null)
            this.setChecked("printingMode", options.printingMode.toString());
         if (options.pageFormat != null)
            this.setSelected("PageFormat", options.pageFormat ?? "A4");
         if (options.bottomPageMargin != null)
            this.containerDivElem.querySelector("#BottomPageMargin").value = options.bottomPageMargin;
         if (options.leftPageMargin != null)
            this.containerDivElem.querySelector("#LeftPageMargin").value = options.leftPageMargin;
         if (options.rightPageMargin != null)
            this.containerDivElem.querySelector("#RightPageMargin").value = options.rightPageMargin;
         if (options.topPageMargin != null)
            this.containerDivElem.querySelector("#TopPageMargin").value = options.topPageMargin;
         if (options.horPageCountLimit != null)
            this.containerDivElem.querySelector("#HorizontalPageCountLimit").value = options.horPageCountLimit;
         if (options.verPageCountLimit != null)
            this.containerDivElem.querySelector("#VerticalPageCountLimit").value = options.verPageCountLimit;
         if (options.zoomFactorInPercent != null)
            this.containerDivElem.querySelector("#ZoomPercentage").value = options.zoomFactorInPercent;
         if (options.bottomTimescaleVisible != null)
            this.containerDivElem.querySelector("#BottomTimescale").checked = options.bottomTimescaleVisible;
         if (options.cutMarksVisible != null)
            this.containerDivElem.querySelector("#CutMarksVisible").checked = options.cutMarksVisible;

         if (options.topHTML != null) {
            this.containerDivElem.querySelector("#TopText").value = options.topHTML;
            this.containerDivElem.querySelector("#TopTextInHTML").checked = true;
         }
         else if (options.topText != null) {
            this.containerDivElem.querySelector("#TopText").value = options.topText;
            this.containerDivElem.querySelector("#TopTextInHTML").checked = false;
         }
         if (options.bottomHTML != null) {
            this.containerDivElem.querySelector("#BottomText").value = options.bottomHTML;
            this.containerDivElem.querySelector("#BottomTextInHTML").checked = true;
         }
         else if (options.bottomText != null) {
            this.containerDivElem.querySelector("#BottomText").value = options.bottomText;
            this.containerDivElem.querySelector("#BottomTextInHTML").checked = false;
         }

         if (options.zoomFactorInPercent)
            this.setChecked("sizing", "1");
         else if ((options.horPageCountLimit != null) || (options.verPageCountLimit != null))
            this.setChecked("sizing", "0");

         if (options.start)
            this.containerDivElem.querySelector("#StartDate").value = (options.start instanceof Date) ? options.start.toISOString() : options.start;
         if (options.end)
            this.containerDivElem.querySelector("#EndDate").value = (options.end instanceof Date) ? options.end.toISOString() : options.end;
      }

      return new Promise((resolve, _reject) => {
         var onClose = () => {
            this.dialog.removeEventListener("close", onClose);
            resolve({ "saveButtonClicked": this.dialog.returnValue === "ok", "pdfOptions": this.options });
            delete this.options;
         };

         this.dialog.addEventListener("close", onClose);
         this.dialog.showModal();
      });
   }
}
