import { ImagePosition } from "@dvn/alaca/components/dvn-card-header/models";
import { BooleanField } from "@dvn/core/doldurma/src/fields/boolean";
import { TextField } from "@dvn/core/doldurma/src/fields/text";
import { ValidatorLength } from "@dvn/core/doldurma/src/interceptors/validators/ValidatorLength";
import { CookieStorage } from "@dvn/kimlik/storage/cookie";
import { SozlukApi } from "@dvn/sozluk/api";
import { Component, h, Prop, State } from "@stencil/core";
import { mentornityAcceptInvitationWrapperI18nDefault, MentornityAcceptInvitationWrapperI18nKey } from "../mentornity-accept-invitation-wrapper/i18n";
export class MentornityAcceptInvitationWidget {
  constructor() {
    this.isProgressing = false;
    this.formFields = () => {
      const defaultFields = [
        new TextField('email', this.strings.email, this.invitation.issuedFor, '').setErrorTitle(this.strings.email)
          .disable(),
        new BooleanField('constent', '', '', SozlukApi.build(this.strings.agreeTermsAndPrivacy, {
          organisationTermsLink: `https://mentornity.com/terms/${this.organisation._id}/organisation`,
          organisationTitle: this.organisation.title,
          policyLink: 'https://mentornity.com/privacy-policy'
        }))
          .setLabelType('markdown')
          .require()
      ];
      if (!this.isLoggedIn) {
        // push password field when the user has not accepted invitation
        defaultFields.splice(1, 0, new TextField('password', this.strings.password, this.strings.definePassword, '').setAutoComplete('off')
          .setErrorTitle(this.strings.password)
          .addInterceptor('onSubmit', new ValidatorLength(6, 24))
          .require());
      }
      return defaultFields;
    };
    this.login = async (email, password) => {
      try {
        const response = await this.api.login(email, password, 'web-client');
        this.storage = new CookieStorage();
        this.storage.save('mt_uid', response.user._id);
        this.storage.save('mt_st', response._id);
        this.storage.save('mt_at', response.accessToken);
      }
      catch (errors) {
        this.formErrors = errors;
      }
    };
    this.saveConsentForPolicy = async () => {
      const redirect = `/${this.organisation.domain}/welcome`;
      const accessToken = this.storage.get('mt_at');
      const sessionToken = this.storage.get('mt_st');
      // set token header
      this.api.addAuthInterceptor(accessToken, sessionToken);
      try {
        const privacyPolicy = await this.api.getPrivacyPolicy(this.language || 'en');
        // save consent if user is logged in
        await this.api.saveConsentForPolicy(this.invitation.invitee._id, privacyPolicy._id, 'invitation');
        window.location = redirect;
      }
      catch (errors) {
        this.formErrors = errors;
      }
    };
    this.onSubmit = async (event) => {
      const { values: { constent, password } } = event.detail;
      this.formErrors = undefined;
      this.isProgressing = true;
      if (constent && (password || this.isLoggedIn)) {
        try {
          await this.api.acceptInvitation(this.invitation._id, password);
          if (!this.isLoggedIn) {
            await this.login(this.invitation.issuedFor, password);
            this.saveConsentForPolicy();
          }
          else {
            window.location = `/${this.organisation.domain}/welcome`;
          }
        }
        catch (errors) {
          this.formErrors = errors;
        }
      }
      this.isProgressing = false;
    };
  }
  async componentWillLoad() {
    this.strings = await this.apiSozluk.getContent(MentornityAcceptInvitationWrapperI18nKey, mentornityAcceptInvitationWrapperI18nDefault);
  }
  render() {
    const { organisation, formErrors, strings, isProgressing } = this;
    return (h("div", { style: { margin: '0 auto', maxWidth: `600px` } },
      h("dvn-card", { leanedSides: true },
        h("dvn-card-header", { title: strings.invitation, slot: "header", showCover: true, coverSrc: organisation.coverUrl || 'https://bit.ly/36goixD', showImage: true, imageSrc: organisation.logoUrl, imageShape: "rounded", imageBorder: true, imagePosition: ImagePosition.BelowCover },
          h("div", { slot: "subtitle" }, organisation.title)),
        h("dvn-markdown", { content: organisation.description })),
      h("dvn-card", { leanedSides: true },
        h("doldurma-form", { fields: this.formFields(), onSubmit: this.onSubmit, submitButtonLabel: strings.submit, progressing: isProgressing, formErrors: formErrors }))));
  }
  static get is() { return "mentornity-accept-invitation-widget"; }
  static get properties() { return {
    "api": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "MentornityApi",
        "resolved": "MentornityApi",
        "references": {
          "MentornityApi": {
            "location": "import",
            "path": "src/modules/mentornity-js-client"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "organisation": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Organisation",
        "resolved": "Organisation",
        "references": {
          "Organisation": {
            "location": "import",
            "path": "src/modules/mentornity-js-client/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiSozluk": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "SozlukApi",
        "resolved": "SozlukApi",
        "references": {
          "SozlukApi": {
            "location": "import",
            "path": "@dvn/sozluk/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "invitation": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "GetInvitation",
        "resolved": "GetInvitation",
        "references": {
          "GetInvitation": {
            "location": "import",
            "path": "src/modules/mentornity-js-client/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "isLoggedIn": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "is-logged-in",
      "reflect": false
    },
    "language": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "language",
      "reflect": false
    }
  }; }
  static get states() { return {
    "strings": {},
    "isProgressing": {},
    "formErrors": {}
  }; }
}
