import { SampleAppResource } from "./SampleData.js";

export default class EditResourceDialog {
   private dialog: HTMLDialogElement;

   /**
    * Initializes the dialog.
    */
   constructor (containerDivElem: HTMLElement) {
      containerDivElem.innerHTML = `
         <dialog id="NETRONIC-VSW-EditResourceDialog" style="width:450px">
            <style>
               #NETRONIC-VSW-EditResourceDialog .textInput {
                  width: 100px;
                  height: 15px;
               }
               #NETRONIC-VSW-EditResourceDialog .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>
            <p></p>
            <span style="color:darkred">To experience dynamic grouping, 
               enable grouping and change the resource properties referenced as grouping criteria here in this dialog. 
               These properties are part of the application data, but not of VSW!
            </span>
            <p></p>
            <label for="groupingProperty1">Your data property 1:  </label>
            <input type="text" class="textInput" id="groupingProperty1"/>
            <p></p>
            <label for="groupingProperty2">Your data property 2:  </label>
            <input type="text" class="textInput" id="groupingProperty2"/>
            <p></p>
            <div class="buttons">
               <button id="OK" autofocus>OK</button>
            </div>
         </dialog>
      `;

      this.dialog = (containerDivElem.querySelector("#NETRONIC-VSW-EditResourceDialog")! as HTMLDialogElement);

      (containerDivElem.querySelector("#OK")! as HTMLButtonElement).addEventListener('click', () => {
         this.dialog.close("ok");
      });
   }

   /**
    * Shows the modal dialog for editing resource properties.
    */
   public showModal (copyOfResource: SampleAppResource): Promise<void> {
      const property1Input = (this.dialog.querySelector("#groupingProperty1")! as HTMLInputElement);
      const property2Input = (this.dialog.querySelector("#groupingProperty2")! as HTMLInputElement);

      // Set current values
      property1Input.value = copyOfResource._GroupingProperty1 ?? "";
      property2Input.value = copyOfResource._GroupingProperty2 ?? "";

      return new Promise((resolve) => {
         const onClose = () => {
            // Update the resource object with new values
            copyOfResource._GroupingProperty1 = property1Input.value ?? "";
            copyOfResource._GroupingProperty2 = property2Input.value ?? "";

            this.dialog.removeEventListener("close", onClose);

            resolve();
         };

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