import { convertValues } from "@dvn/core/components/views/dvn-card-view/action-util";
import { generateFieldModelFromRawData } from "@dvn/core/doldurma/src/FieldModelGenerator";
import { SingleChoiceField } from "@dvn/core/doldurma/src/fields/single-choice";
import { findField } from "@dvn/core/util/field";
import { SozlukApi } from "@dvn/sozluk/api";
import { Component, h, Prop, State } from "@stencil/core";
import { createMentornityApiInstance } from "src/modules/mentornity-js-client";
import { mentornityApiEndpoint } from "../../constants/env";
import { getSessionDetails } from "../../util/session";
import { mentornityAnnouncementWrapperI18nDefault, MentornityAnnouncementWrapperI18nKey } from "../mentornity-announcements-page-wrapper/i18n";
import { sozlukEntries } from "../sozluk-entries";
import { getFormParameters, getFormViewConfig } from "./wrapper-util";
function getFieldFromFormFieldConfig(fields, fieldData) {
  return fieldData.field || findField(fields, fieldData.fieldId);
}
// sets value if the parameters contain value for fields
const prepareFields = (view, params = {}) => {
  const data = convertValues(view.conversionConfig, params);
  return view.ui.fields.map(formFieldConfig => {
    var _a;
    const field = generateFieldModelFromRawData(getFieldFromFormFieldConfig(view.table.fields, formFieldConfig));
    const value = data[field.id];
    if (value && field.type === SingleChoiceField.type) {
      const singleChoice = field;
      if (singleChoice.dataProvider) {
        // dvn-select doesn't show any data if it has a data provider (meaning that the options are not set)
        // we need to pass initial options with the selected value in it
        singleChoice.dataProvider.setInitialData([value]);
      }
      field.setValue(((_a = singleChoice.dataAdapter) === null || _a === void 0 ? void 0 : _a.value(value)) || value);
    }
    else if (value) {
      field.setValue(value);
    }
    return field;
  });
};
export class MentornityUserMetadataForm {
  constructor() {
    this.isFetching = false;
    this.isProgressing = false;
    this.setDictionary = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      // using common strings of announcement dictionary
      this.strings = await apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    };
    this.onSubmit = (event, view) => {
      if (!view.handler.onSubmit) {
        return;
      }
      this.isProgressing = true;
      this.formErrors = undefined;
      view.handler.onSubmit(event).then(() => {
        this.isProgressing = false;
        window.dispatchEvent(new CustomEvent('dvn.mentornity-user-metadata-form.go-next-step'));
      }).catch(errors => {
        this.isProgressing = false;
        this.formErrors = errors;
      });
    };
  }
  componentWillLoad() {
    const { context: { organisationId, role, userId }, headers } = getSessionDetails();
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId).then((response) => {
      this.organisationConfig = response;
    });
    this.setDictionary();
    this.isFetching = true;
    mentornityApi.getMetadataOfUser(organisationId, role === 'mentor' ? 'mentors' : 'mentees', userId)
      .then(response => {
      this.userMetadata = response;
    });
    this.isFetching = false;
  }
  render() {
    var _a, _b;
    if (this.isFetching || !this.userMetadata || !this.organisationConfig || !this.strings) {
      return (h("mentornity-root-wrapper", null,
        h("div", { class: "d-flex justify-content-center pt-3" },
          h("dvn-progress", { indefinite: true }))));
    }
    const { context } = getSessionDetails();
    const params = getFormParameters(context, this.organisationConfig, this.userMetadata);
    const view = getFormViewConfig(context, this.organisationConfig, this.userMetadata);
    const hasMetadata = ((_b = (_a = view.table) === null || _a === void 0 ? void 0 : _a.fields) === null || _b === void 0 ? void 0 : _b.length) > 0;
    return (h("mentornity-root-wrapper", null,
      !hasMetadata &&
        h("p", null, this.strings.noMetadataFound),
      h("doldurma-form", { fields: prepareFields(view, params), onSubmit: (event) => this.onSubmit(event, view), submitButtonLabel: hasMetadata ? `${this.strings.save} & ${this.strings.next}` : this.strings.next, progressing: this.isProgressing, formErrors: this.formErrors })));
  }
  static get is() { return "mentornity-user-metadata-form"; }
  static get properties() { return {
    "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": {},
    "userMetadata": {},
    "organisationConfig": {},
    "isFetching": {},
    "isProgressing": {},
    "formErrors": {}
  }; }
}
