import { coreState } from "@corejam/core-components";
import { runState } from "@corejam/run";
import { Component, Element, h, Host, Listen, Prop, State } from "@stencil/core";
import gql from "graphql-tag";
import { userAuthenticateMutationGQL } from "../../../shared/graphql/Mutations";
import { authStore } from "../../store/authStore";
/**
 * Component to handle authentication state / refresh.
 */
export class CorejamIdentity {
  constructor() {
    this.formId = "identity";
    this.loginLink = "/login/";
    this.registerLink = "/register/";
    this.dropdown = false;
    this.toggleMenu = () => {
      this.dropdown = !this.dropdown;
    };
    this.logOut = () => {
      this.toggleMenu();
      authStore.identity = null;
    };
  }
  handleClick(ev) {
    let shouldClose = true;
    //Check if dropdown is open
    if (this.dropdown) {
      //Check if path doesnt have identity component in it
      ev.composedPath().forEach((element) => {
        if (element === this.element) {
          shouldClose = false;
        }
      });
      //Close it if it doesnt
      if (shouldClose) {
        this.toggleMenu();
      }
    }
  }
  componentWillLoad() {
    this.setRefreshTimer();
  }
  /**
   * Based on the token expiry we send a refresh request which
   * includes the refreshToken from cookies
   */
  setRefreshTimer() {
    setTimeout(() => {
      console.log("Refreshing token");
    }, 10000); //Time needs to come from this.token.expiry
  }
  async formEventHandler({ detail }) {
    if (detail.formId != this.formId || authStore.identity)
      return;
    const request = await coreState.client.mutate({
      mutation: gql(userAuthenticateMutationGQL),
      variables: {
        email: detail.email.value,
        password: detail.password.value,
      },
    });
    if (request.data.userAuthenticate) {
      this.toggleMenu();
      authStore.identity = request.data.userAuthenticate;
      runState.router.push("/");
    }
  }
  render() {
    return (h(Host, null,
      h("corejam-box", { position: "relative", flex: true, direction: "row", justify: "end" },
        authStore.identity ? (h("corejam-box", { pr: 3 },
          h("corejam-type", { "data-cy": "identity-email" }, authStore.identity.user.email))) : null,
        h("corejam-icons-account", { onClick: () => this.toggleMenu() }),
        h("corejam-box", { bg: "white", shadow: "0px 0px 10px rgba(0, 0, 0, 0.1)", position: "absolute", top: 30, right: 5, p: 4, rounded: "md", w: "250px", style: { display: this.dropdown ? "initial" : "none" } }, authStore.identity ? (h("corejam-box", { w: "12", flex: true, direction: "col" },
          h("corejam-box", null,
            h("corejam-base-link", { href: "/account" }, "My Account")),
          h("corejam-box", { onClick: () => {
              this.logOut();
            } }, "Log out"))) : (h("corejam-form-container", { name: this.formId },
          h("corejam-flash", { "data-flash": "isolated" }),
          h("corejam-box", { pb: 3, flex: true, direction: "col" },
            h("corejam-box", { w: "12" },
              h("corejam-form-input", { name: "email", type: "text", formId: this.formId, label: "Email" }),
              h("corejam-form-input", { name: "password", type: "password", formId: this.formId, label: "Password" })),
            h("corejam-box", { flex: true, direction: "row", w: "12", mt: 4 },
              h("corejam-box", { w: "6", bg: "gray-200", rounded: "md", flex: true, justify: "center" },
                h("corejam-form-submit", { formId: this.formId },
                  h("corejam-button", { type: "button", color: "gray-900", pl: "5", pr: "5", pt: "3", pb: "3" },
                    h("corejam-type", null, "Login")))),
              h("corejam-box", { w: "6", flex: true, justify: "center", items: "center" },
                h("corejam-base-link", { href: "/register" }, "Register"))))))))));
  }
  static get is() { return "corejam-identity"; }
  static get properties() { return {
    "loginLink": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "login-link",
      "reflect": false,
      "defaultValue": "\"/login/\""
    },
    "registerLink": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "register-link",
      "reflect": false,
      "defaultValue": "\"/register/\""
    }
  }; }
  static get states() { return {
    "dropdown": {}
  }; }
  static get elementRef() { return "element"; }
  static get listeners() { return [{
      "name": "click",
      "method": "handleClick",
      "target": "document",
      "capture": false,
      "passive": false
    }, {
      "name": "sendForm",
      "method": "formEventHandler",
      "target": "window",
      "capture": false,
      "passive": false
    }]; }
}
