import {Controller} from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["notifications"];
  static values = {
    url: String,
  };

  initialize() {
    this.checkFlashes = this.checkFlashes.bind(this);
  }

  connect() {
    this.checkFlashes();
    window.addEventListener("live:saved", this.checkFlashes);
  }

  disconnect() {
    window.removeEventListener("live:saved", this.checkFlashes);
  }

  checkFlashes() {
    const flashes = this.getCookie("flashes");
    if (flashes) {
      try {
        const data = JSON.parse(decodeURIComponent(flashes.replace(/\+/g, " ")));
        if (typeof data === "object" && data !== null) {
          Object.entries(data).forEach(([type, messages]) => {
            if (Array.isArray(messages)) {
              messages.forEach((message) => {
                this.renderFlash(type, message);
              });
            }
          });
        }
      } catch (e) {
        console.error("Failed to parse flashes cookie", e);
      }

      this.clearCookie("flashes");
    }
  }

  async renderFlash(type, message) {
    const url = new URL(this.urlValue, window.location.origin);
    if (typeof message === "object" && message !== null) {
      Object.entries(message).forEach(([key, value]) => {
        if (value !== null && value !== undefined) {
          url.searchParams.set(key, value);
        }
      });

      if (!url.searchParams.has("type")) {
        url.searchParams.set("type", type);
      }
    } else {
      url.searchParams.set("type", type);
      url.searchParams.set("title", message || "");
    }

    const response = await fetch(url, {
      headers: {
        Accept: "text/vnd.turbo-stream.html",
      },
    });

    if (response.ok) {
      const stream = await response.text();
      document.body.insertAdjacentHTML("beforeend", stream);
    }
  }

  getCookie(cname) {
    const name = cname + "=";
    const ca = document.cookie.split(';');
    for(let i=0; i<ca.length; i++) {
      const c = ca[i].trim();
      if (c.indexOf(name)===0) {
        return c.substring(name.length,c.length);
      }
    }

    return false;
  }


  clearCookie(cname) {
    document.cookie = `${cname}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
  }
}
