import { Controller } from "@hotwired/stimulus"

const LEAVE_ALERT = "Es gibt ungespeicherte Änderungen! Wirklich verlassen?"

// Connects to data-controller="unsaved-changes"
export default class extends Controller {
  static targets = ["cancel"]

  initialState = null

  connect() {
    this.initialState = this.formState()
    console.log(this.cancelTargets)

    window.addEventListener("beforeunload", (event) => this.leavingPage(event))
    document.addEventListener('turbo:before-visit', (e) => this.leavingPage(e))
    this.element.addEventListener("submit", (_) => this.initialState = null)
    this.cancelTargets.forEach(element => {
      console.log(element)
      element.addEventListener("onclick", (_) => this.initialState = null)
    });
  }

  formState() {
    return JSON.stringify(Array.from(new FormData(this.element).entries())
      .filter(x => x[1] != "")
      .sort(x => x[0]))
  }

  leavingPage(event) {
    console.log(event.type)
    if (this.initialState == null || this.initialState == this.formState()) {
      return
    }
    if (event.type == "turbo:before-visit") {
      if (!window.confirm(LEAVE_ALERT)) {
        event.preventDefault()
      } else {
        this.initialState = null
      }
    } else {
      this.initialState = null
      event.returnValue = LEAVE_ALERT;
      return event.returnValue;
    }
  }
}