import { r as registerInstance, h, H as Host, c as createEvent, g as getElement } from './index-ecdfb761.js';
import { S as SozlukApi } from './index-3bf9b308.js';
import { s as sozlukEntries, d as MentornityAnnouncementWrapperI18nKey, e as mentornityAnnouncementWrapperI18nDefault } from './sozluk-entries-1e8f5234.js';
import { C as CalendarUtils } from './calendar-470c802a.js';
import { D as DataModel } from './data-model-88af49fc.js';
import { A as APIBase } from './apiBase-6015f41f.js';
import { T as TextField } from './index-150b6a59.js';
import { T as TableListViewConfig } from './table-list-view-config-6e2aee35.js';
import { A as AppViewType } from './view-config-1ed8c59f.js';
import { g as getSessionDetails, m as mentornityApiEndpoint } from './session-2a491341.js';
import './i18n-09a07b97.js';
import './i18n-0e757ca5.js';
import './index-a3ca021c.js';
import './_commonjsHelpers-27f122dd.js';
import './moment-65eca6b3.js';
import './data-transfer-field-2f305919.js';
import './BaseField-0b01dc2c.js';
import './filter-cbaa3d7d.js';
import './FieldGenerator-3ae403b2.js';
import './table-config-d73a72ab.js';
import './FieldModelGenerator-378c8613.js';
import './reference-field-a5b414d1.js';
import './index-61dcd269.js';
import './date-1bc489bd.js';
import './index-4e451db4.js';
import './index-23baeeef.js';
import './index-09efdc01.js';
import './membership-b6639471.js';
import './string-3065a411.js';
import './User-72c4643a.js';
import './UserSettings-7e4170a7.js';
import './cookie-5d9f5819.js';
import './kimlik-api-fddeac81.js';
import './index-d3bd30bd.js';
import './mentorinty-bridge-api-5ca2d652.js';
import './index-e66e8eca.js';
import './attachment-961dd228.js';
import './CalendarConfig-412d1b0f.js';

const dvnStepperCss = "dvn-stepper .step{font-size:var(--font-size-large);margin-right:var(--spacing-unit)}dvn-stepper .active{background-color:var(--color-background-primary);padding:calc(2 * var(--spacing-unit));border-radius:calc(2 * var(--spacing-unit));font-weight:bold}dvn-stepper .clickable{cursor:pointer}";

const DvnStepper = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.activeStep = 0;
    this.allowToClickNextSteps = false; // not allow to click a step bigger then active step
    this.scale = 'medium';
  }
  render() {
    const { steps, activeStep, scale } = this;
    const hasClickableSteps = !!this.stepOnClick;
    return (h(Host, null, h("div", { class: "d-flex mb-4 align-items-baseline" }, steps && steps.map((step, i) => (h("div", null, h("span", { class: `step ${activeStep === i ? 'active' : ''} ${hasClickableSteps && (this.allowToClickNextSteps || activeStep > i) ? 'clickable' : ''}`, style: { fontSize: `var(--font-size-${scale})` }, onClick: () => {
        if (this.allowToClickNextSteps || activeStep > i) {
          this.stepOnClick(i);
        }
      } }, step.label), steps.length - 1 !== i &&
      h("dvn-icon", { iconName: "uil uil-angle-right-b", size: 20, style: { color: 'var(--color-text-secondary)' } })))))));
  }
};
DvnStepper.style = dvnStepperCss;

const MentornityCreateAnnouncementForm = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.previewAsUser = createEvent(this, "previewAsUser", 7);
    this.getCurrentAnnouncement = createEvent(this, "getCurrentAnnouncement", 7);
    this.announcementForm = {
      title: '',
      content: 'Form Description'
    };
    this.editorValue = [
      {
        type: 'text',
        id: 'form-content',
        value: {
          placeholder: 'Form Description',
          text: '',
        },
      },
    ];
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    };
  }
  componentWillLoad() {
    this.setDictionaryLanguage();
    const isUpdatingAnnouncement = !!this.editableAnnouncement;
    if (isUpdatingAnnouncement) {
      this.announcementForm = this.editableAnnouncement;
      // @ts-ignore
      this.announcementForm.content = new showdown.Converter().makeHtml(this.editableAnnouncement.content);
      const editorValue = JSON.parse(JSON.stringify(this.editorValue));
      editorValue[0].value.text = this.announcementForm.content;
      this.editorValue = editorValue;
    }
    this.getCurrentAnnouncement.emit(this.announcementForm);
  }
  render() {
    var _a;
    const { strings } = this;
    if (!strings)
      return;
    return (h("div", { class: "container" }, h("div", { class: "row" }, h("div", { class: "col-md-12" }, h("h4", null, strings.title), h("dvn-input", { leaned: true, class: "mb-3", placeholder: strings.writeTitleOfAnnouncement, scale: "large", width: "100%", value: (_a = this.editableAnnouncement) === null || _a === void 0 ? void 0 : _a.title, onChange: (e) => {
        this.announcementForm.title = e.detail;
        this.getCurrentAnnouncement.emit(this.announcementForm);
      } })), h("div", { class: "col-md-12" }, h("div", { class: "d-flex justify-content-between" }, h("h4", null, strings.content), h("div", { style: { textAlign: 'end' } }, h("dvn-button", { class: "ml-3", leaned: true, view: 'outline', onClick: () => this.previewAsUser.emit(this.announcementForm) }, h("div", { class: "d-flex align-items-center" }, h("dvn-icon", { iconName: "uil uil-eye", scale: "large" }), strings.previewAsUser)))), h("dvn-card", { height: "350px", leanedSides: true, outlined: true, cornerRadius: 5 }, h("dvn-rich-editor", { key: "editor", onChange: (e) => {
        var _a;
        const editorValue = e.detail;
        this.announcementForm.content = (_a = editorValue[0]) === null || _a === void 0 ? void 0 : _a.value.text;
        this.editorValue = editorValue;
        this.getCurrentAnnouncement.emit(this.announcementForm);
      }, editorSettings: {
        enableDrag: false,
        enableBlockCreation: false,
        enableBlockDeletion: false,
        hideDragControls: true,
        blockTypes: [],
        blockSettings: {
          text: {
            textSelectionOptions: ['bold', 'link']
          }
        }
      }, value: this.editorValue }))))));
  }
  get el() { return getElement(this); }
};

class MentornityAnnouncementPublishBridgeApi {
  constructor(selectedUsers) {
    this.selectedUsers = selectedUsers;
  }
  addAuthInterceptor(_token) {
    // console.log('MBA.addAuthInterceptor', token);
  }
  // region DataApi
  get(_collection, _id, _query) {
    return undefined;
  }
  query() {
    return new Promise((resolve => {
      resolve({
        results: this.selectedUsers.map((item) => DataModel.decode(Object.assign({ _id: item._id }, (item || {})))),
        meta: {
          total: this.selectedUsers.length,
        }
      });
    }));
  }
  getRoleForFetching(role) {
    if (role === 'mentorsCustom') {
      return 'mentors';
    }
    else if (role === 'menteesCustom') {
      return 'mentees';
    }
    else {
      return role;
    }
  }
  update(_collection, _id, _body) {
    return undefined;
  }
}

const MentornityAnnouncementPublish = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.updateStatusAnnouncement = createEvent(this, "updateStatusAnnouncement", 7);
    this.sendEmails = createEvent(this, "sendEmails", 7);
    this.openAnnouncementReport = createEvent(this, "openAnnouncementReport", 7);
    this.showErrorMessage = createEvent(this, "showErrorMessage", 7);
    this.itemsSelectedCount = 0;
    this.isLoading = false;
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    };
  }
  componentWillLoad() {
    this.api = new MentornityAnnouncementPublishBridgeApi(this.selectedUsers);
    this.setDictionaryLanguage();
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const { strings } = this;
    if (!strings)
      return;
    const hasSentEmails = ((_b = (_a = this.announcement) === null || _a === void 0 ? void 0 : _a.targetList) === null || _b === void 0 ? void 0 : _b.length) > 0;
    const sentEmailsAt = ((_d = (_c = this.announcement) === null || _c === void 0 ? void 0 : _c.sentEmailsAt) === null || _d === void 0 ? void 0 : _d.length) > 0 && CalendarUtils.format(((_e = this.announcement) === null || _e === void 0 ? void 0 : _e.sentEmailsAt[((_g = (_f = this.announcement) === null || _f === void 0 ? void 0 : _f.sentEmailsAt) === null || _g === void 0 ? void 0 : _g.length) - 1]) * 1000, `DD-MM-YYYY - ${CalendarUtils.timeFormat === '12-hour' ? 'hh:mm A' : 'HH:mm'}`); // get latest sent date
    const hasSelectedUsers = this.selectedUsers.length > 0;
    return (h(Host, { class: "row", style: { overflow: 'hidden' } }, h("div", { class: "col-12" }, h("dvn-card", { leanedSides: true, outlined: true, cornerRadius: 5 }, h("div", { class: "d-flex justify-content-between align-items-center" }, h("div", null, h("h4", null, strings.publishOnPlatform), h("p", null, strings.publishDescription)), h("dvn-switch", { tint: "secondary", scale: "small", onChange: () => this.updateStatusAnnouncement.emit(this.announcement), checked: ((_h = this.announcement) === null || _h === void 0 ? void 0 : _h.status) === 'published' ? true : false })))), h("div", { class: "col-12" }, h("dvn-card", { leanedSides: true, outlined: true, cornerRadius: 5 }, !hasSelectedUsers &&
      h("dvn-alert", { tint: "danger", message: strings.usersSelectedAlert }), h("div", { class: "d-flex justify-content-between align-items-center" }, h("div", null, h("h4", null, strings.mailing), h("p", null, strings.mailingDescription)), h("dvn-button", { tint: "primary", leaned: true, disabled: !hasSelectedUsers, onClick: () => {
        if (hasSelectedUsers)
          this.sendEmails.emit();
      } }, strings.startMailing)), hasSentEmails &&
      h("div", { class: "d-flex align-items-center" }, h("p", { style: { color: 'var(--color-neutral)' }, class: "mb-0 mr-2" }, " ", strings.lastMailing, " ", sentEmailsAt), h("strong", { style: { cursor: 'pointer' }, onClick: () => this.openAnnouncementReport.emit(this.announcement) }, strings.checkReport))))));
  }
};

class MentornityAnnouncementReportBridgeApi {
  constructor(announcementId, endpoint, headers, strings) {
    this.client = new APIBase(endpoint, headers);
    this.announcementId = announcementId;
    this.strings = strings;
  }
  addAuthInterceptor(_token) {
    // console.log('MBA.addAuthInterceptor', token);
  }
  // region DataApi
  get(_collection, _id, _query) {
    return undefined;
  }
  update(_collection, _id, _body) {
    return undefined;
  }
  async query(_collection) {
    return new Promise((resolve => {
      this.client.get(`announcements/${this.announcementId}/email-report`).then(response => {
        resolve({
          results: response.results.map((item) => {
            var _a, _b;
            return DataModel.decode(Object.assign(Object.assign({ _id: item.recipient[0]._id }, (item.recipient[0] || {})), { firstName: item.recipient[0].firstName, lastName: item.recipient[0].lastName, email: item.recipient[0].email, status: ((_a = item.metadata) === null || _a === void 0 ? void 0 : _a.delivered) ? ((_b = item.metadata) === null || _b === void 0 ? void 0 : _b.opened) ? this.strings.opened : this.strings.delivered : this.strings.pending }));
          }),
          meta: {
            total: response.results.length,
          }
        });
      }).catch(e => {
        console.log(e);
      });
    }));
  }
}
const MentornityAnnouncementReport = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.setDictionary = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    };
  }
  async componentWillLoad() {
    const { headers } = getSessionDetails();
    await this.setDictionary();
    this.api = new MentornityAnnouncementReportBridgeApi(this.announcementId, mentornityApiEndpoint, headers, this.strings);
    this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
  }
  render() {
    const listViewConfig = viewConfig$1(this.strings);
    return (h(Host, { class: "row", style: { overflow: 'hidden' } }, h("div", { class: "col-12" }, h("dvn-app-view-list-view-table", { apiData: this.api, apiSozluk: this.apiSozluk, view: listViewConfig, style: { height: '500px' } }))));
  }
};
const viewConfig$1 = (i18n) => {
  const columns = {
    'firstName': {
      width: 200
    },
    'lastName': {
      width: 200
    },
    'email': {
      width: 200
    }
  };
  return TableListViewConfig.decode({
    _id: 'mentornity-announcement-report',
    i18nEntryId: 'mentornity-announcement-report',
    type: AppViewType.ListViewTable,
    base: 'mentornity3',
    title: i18n.mailingReport,
    table: {
      fields: [
        new TextField('firstName', i18n.firstName),
        new TextField('lastName', i18n.lastName),
        new TextField('email', i18n.email),
        new TextField('status', i18n.status),
      ],
    },
    query: {},
    ui: TableListViewConfig.decode({
      main: {
        actionsPlacement: 'left',
        fields: [
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          { fieldId: 'email' },
          { fieldId: 'status' },
        ],
        columns
      }
    })
  });
};

class MentornityAnnouncementSelectUsersBridgeApi {
  constructor(organisationId, endpoint, headers, config, onRoleChange, onDataChange, onFetchingChange) {
    this.client = new APIBase(endpoint, headers);
    this.organisationId = organisationId;
    this.config = config;
    this.onDataChange = onDataChange;
    this.onRoleChange = onRoleChange;
    this.onFetchingChange = onFetchingChange;
  }
  addAuthInterceptor(_token) {
    // console.log('MBA.addAuthInterceptor', token);
  }
  // region DataApi
  get(_collection, _id, _query) {
    return undefined;
  }
  async query(_collection) {
    let role = this.getRoleForFetching(_collection) || 'mentors';
    this.onRoleChange(_collection);
    this.onFetchingChange();
    const data = await new Promise((resolve => {
      this.client.get(`organisations/${this.organisationId}/${role}`, { includePassiveMentors: true, expandMetadatas: true }).then(response => {
        var _a, _b;
        role = role === 'all' ? role : role.substring(0, role.length - 1);
        let results = response.results;
        if (role === 'all') {
          results = [...(_a = response.mentors) === null || _a === void 0 ? void 0 : _a.results, ...(_b = response.mentees) === null || _b === void 0 ? void 0 : _b.results];
        }
        resolve({
          results: results.map((user) => {
            var _a;
            let metadata = {};
            if (role !== 'all') {
              (_a = this.config) === null || _a === void 0 ? void 0 : _a.metadatas[role].forEach(field => {
                metadata[field.id] = this.getMetadataValue(user, field);
              });
            }
            return DataModel.decode(Object.assign(Object.assign({ _id: user._id }, (user || {})), metadata));
          }),
          meta: {
            total: results.length,
          }
        });
      }).catch(e => {
        console.log(e);
      });
    }));
    this.onFetchingChange();
    this.onDataChange(data);
    return data;
  }
  getRoleForFetching(role) {
    if (role === 'customMentor') {
      return 'mentors';
    }
    else if (role === 'customMentee') {
      return 'mentees';
    }
    else if (role === 'all') {
      return role;
    }
    else {
      return role + 's';
    }
  }
  getMetadataValue(user, field) {
    var _a;
    const refField = (_a = user === null || user === void 0 ? void 0 : user.metadata) === null || _a === void 0 ? void 0 : _a.data[field.id];
    switch (field.type) {
      case 'ratingStars':
        return Math.floor(refField * 5) || '';
      case 'multipleChoice':
        let string = '';
        (refField || []).forEach((label, i) => {
          string += label + `${(refField === null || refField === void 0 ? void 0 : refField.length) - 1 > i ? ', ' : ''}`;
        });
        return string;
      default:
        return refField;
    }
  }
  update(_collection, _id, _body) {
    return undefined;
  }
}

const MentornityAnnouncementSelectUsers = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.setAnnouncementRole = createEvent(this, "setAnnouncementRole", 7);
    this.itemsSelectedCount = 0;
    this.shownRole = 'mentor';
    this.isLoading = false;
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    };
    this.onFetchingChange = () => {
      this.isLoading = !this.isLoading;
    };
    this.onRoleChange = async (role) => {
      this.setSelectedItems([]);
      this.itemsSelectedCount = 0;
      await this.setAnnouncementRole.emit(role);
    };
    this.onDataChange = (data) => {
      var _a;
      if (this.shownRole === 'mentor' || this.shownRole === 'mentee' || this.shownRole === 'all') {
        this.itemsSelectedCount = (_a = data.results) === null || _a === void 0 ? void 0 : _a.length;
        this.setSelectedItems(data.results);
      }
      this.data = data;
    };
  }
  async componentWillLoad() {
    const { context, headers } = getSessionDetails();
    this.api = new MentornityAnnouncementSelectUsersBridgeApi(context.organisationId, mentornityApiEndpoint, headers, this.organisationConfig, this.onRoleChange, this.onDataChange, this.onFetchingChange);
    this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
    this.setDictionaryLanguage();
  }
  getRole(role) {
    if (role === 'customMentor') {
      return 'mentor';
    }
    else if (role === 'customMentee') {
      return 'mentee';
    }
    else {
      return role;
    }
  }
  render() {
    var _a;
    const { strings } = this;
    if (!strings)
      return;
    const role = this.getRole(this.shownRole);
    const metadata = (_a = this.organisationConfig) === null || _a === void 0 ? void 0 : _a.metadatas[role];
    const listViewConfig = viewConfig(metadata, strings, this.shownRole);
    const isCustomTarget = ['customMentor', 'customMentee'].includes(this.shownRole);
    return (h(Host, { class: "row", style: { overflow: 'hidden' } }, h("div", { class: "col-12" }, h("div", { class: "d-flex align-items-center" }, h("dvn-select", { class: "ml-3", value: 'mentor', onChange: (event) => this.shownRole = event.detail }, h("dvn-select-option", { value: 'all' }, strings.all), h("dvn-select-option", { value: 'mentor' }, strings.mentor), h("dvn-select-option", { value: 'customMentor' }, strings.customMentor), h("dvn-select-option", { value: 'mentee' }, strings.mentee), h("dvn-select-option", { value: 'customMentee' }, strings.customMentee)), this.itemsSelectedCount > 0 && h("p", { class: "m-0" }, SozlukApi.build(strings.selectedUsersCount, { count: this.itemsSelectedCount }))), !isCustomTarget &&
      h("div", { class: "ml-3", style: {
          margin: '70px auto',
          textAlign: 'center',
          color: 'var(--color-neutral)'
        } }, this.isLoading ?
        h("dvn-progress", { indefinite: true })
        :
          h("p", null, strings.selectedAllTarget))), h("div", { class: "col-12" }, h("dvn-app-view-list-view-table", { key: this.shownRole, apiData: this.api, apiSozluk: this.apiSozluk, view: listViewConfig, style: { height: isCustomTarget ? '500px' : '0px', opacity: isCustomTarget ? '1' : '0' }, onRowSelection: (data) => {
        this.itemsSelectedCount = data === null || data === void 0 ? void 0 : data.length;
        this.setSelectedItems(data);
      }, checkboxSelection: this.shownRole === 'customMentor' || this.shownRole === 'customMentee' ? true : false }))));
  }
  get el() { return getElement(this); }
};
const viewConfig = (metadata, i18n, role) => {
  const columns = {
    'email': {
      width: 300
    }
  };
  (metadata || []).forEach(data => {
    columns[data.id] = {
      width: 200
    };
  });
  return TableListViewConfig.decode({
    _id: 'mentornity-announcement-select-users',
    i18nEntryId: 'mentornity-announcement-select-users',
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    table: {
      name: role,
      fields: [
        new TextField('firstName', i18n.firstName),
        new TextField('lastName', i18n.lastName),
        new TextField('email', i18n.email),
        ...(metadata || []).map(data => new TextField(data.id, data.title))
      ],
    },
    query: {},
    ui: TableListViewConfig.decode({
      main: {
        actionsPlacement: 'left',
        fields: [
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          { fieldId: 'email' },
          ...(metadata || []).map(data => ({ fieldId: data.id }))
        ],
        columns,
      }
    }),
  });
};

export { DvnStepper as dvn_stepper, MentornityCreateAnnouncementForm as mentornity_announcement_form, MentornityAnnouncementPublish as mentornity_announcement_publish, MentornityAnnouncementReport as mentornity_announcement_report, MentornityAnnouncementSelectUsers as mentornity_announcement_select_users };
