'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-1141a245.js');
const index$1 = require('./index-a2e99c85.js');
const sozlukEntries = require('./sozluk-entries-3b9686e7.js');
const calendar = require('./calendar-e4b7baeb.js');
const dataModel = require('./data-model-01c368bc.js');
const apiBase = require('./apiBase-6c66ff1b.js');
const index$2 = require('./index-61f9621a.js');
const tableListViewConfig = require('./table-list-view-config-a7907d79.js');
const viewConfig$2 = require('./view-config-52c16db0.js');
const session = require('./session-f588baa3.js');
require('./i18n-0bcf144d.js');
require('./i18n-77d45414.js');
require('./index-b776fc14.js');
require('./_commonjsHelpers-206db00d.js');
require('./moment-7a3433f2.js');
require('./data-transfer-field-e8417d5f.js');
require('./BaseField-381327a9.js');
require('./filter-d5040f65.js');
require('./FieldGenerator-279a646b.js');
require('./table-config-969d3038.js');
require('./FieldModelGenerator-d61f01d4.js');
require('./reference-field-1239b0c3.js');
require('./index-2eea69a0.js');
require('./date-a24d7714.js');
require('./index-0783d14f.js');
require('./index-9d3d3d15.js');
require('./index-9fd84b93.js');
require('./membership-e87e02ed.js');
require('./string-de672b69.js');
require('./User-dbfbd45e.js');
require('./UserSettings-2a2399b1.js');
require('./cookie-e64bc800.js');
require('./kimlik-api-663f4884.js');
require('./index-33e96540.js');
require('./mentorinty-bridge-api-b1eaa56d.js');
require('./index-b7855ed6.js');
require('./attachment-a0cdf203.js');
require('./CalendarConfig-998f742e.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) {
    index.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 (index.h(index.Host, null, index.h("div", { class: "d-flex mb-4 align-items-baseline" }, steps && steps.map((step, i) => (index.h("div", null, index.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 &&
      index.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) {
    index.registerInstance(this, hostRef);
    this.previewAsUser = index.createEvent(this, "previewAsUser", 7);
    this.getCurrentAnnouncement = index.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 index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
      this.strings = await apiSozluk.getContent(sozlukEntries.MentornityAnnouncementWrapperI18nKey, sozlukEntries.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 (index.h("div", { class: "container" }, index.h("div", { class: "row" }, index.h("div", { class: "col-md-12" }, index.h("h4", null, strings.title), index.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);
      } })), index.h("div", { class: "col-md-12" }, index.h("div", { class: "d-flex justify-content-between" }, index.h("h4", null, strings.content), index.h("div", { style: { textAlign: 'end' } }, index.h("dvn-button", { class: "ml-3", leaned: true, view: 'outline', onClick: () => this.previewAsUser.emit(this.announcementForm) }, index.h("div", { class: "d-flex align-items-center" }, index.h("dvn-icon", { iconName: "uil uil-eye", scale: "large" }), strings.previewAsUser)))), index.h("dvn-card", { height: "350px", leanedSides: true, outlined: true, cornerRadius: 5 }, index.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 index.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.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) {
    index.registerInstance(this, hostRef);
    this.updateStatusAnnouncement = index.createEvent(this, "updateStatusAnnouncement", 7);
    this.sendEmails = index.createEvent(this, "sendEmails", 7);
    this.openAnnouncementReport = index.createEvent(this, "openAnnouncementReport", 7);
    this.showErrorMessage = index.createEvent(this, "showErrorMessage", 7);
    this.itemsSelectedCount = 0;
    this.isLoading = false;
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
      this.strings = await apiSozluk.getContent(sozlukEntries.MentornityAnnouncementWrapperI18nKey, sozlukEntries.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 && calendar.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 - ${calendar.CalendarUtils.timeFormat === '12-hour' ? 'hh:mm A' : 'HH:mm'}`); // get latest sent date
    const hasSelectedUsers = this.selectedUsers.length > 0;
    return (index.h(index.Host, { class: "row", style: { overflow: 'hidden' } }, index.h("div", { class: "col-12" }, index.h("dvn-card", { leanedSides: true, outlined: true, cornerRadius: 5 }, index.h("div", { class: "d-flex justify-content-between align-items-center" }, index.h("div", null, index.h("h4", null, strings.publishOnPlatform), index.h("p", null, strings.publishDescription)), index.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 })))), index.h("div", { class: "col-12" }, index.h("dvn-card", { leanedSides: true, outlined: true, cornerRadius: 5 }, !hasSelectedUsers &&
      index.h("dvn-alert", { tint: "danger", message: strings.usersSelectedAlert }), index.h("div", { class: "d-flex justify-content-between align-items-center" }, index.h("div", null, index.h("h4", null, strings.mailing), index.h("p", null, strings.mailingDescription)), index.h("dvn-button", { tint: "primary", leaned: true, disabled: !hasSelectedUsers, onClick: () => {
        if (hasSelectedUsers)
          this.sendEmails.emit();
      } }, strings.startMailing)), hasSentEmails &&
      index.h("div", { class: "d-flex align-items-center" }, index.h("p", { style: { color: 'var(--color-neutral)' }, class: "mb-0 mr-2" }, " ", strings.lastMailing, " ", sentEmailsAt), index.h("strong", { style: { cursor: 'pointer' }, onClick: () => this.openAnnouncementReport.emit(this.announcement) }, strings.checkReport))))));
  }
};

class MentornityAnnouncementReportBridgeApi {
  constructor(announcementId, endpoint, headers, strings) {
    this.client = new apiBase.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.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) {
    index.registerInstance(this, hostRef);
    this.setDictionary = async () => {
      const apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
      this.strings = await apiSozluk.getContent(sozlukEntries.MentornityAnnouncementWrapperI18nKey, sozlukEntries.mentornityAnnouncementWrapperI18nDefault);
    };
  }
  async componentWillLoad() {
    const { headers } = session.getSessionDetails();
    await this.setDictionary();
    this.api = new MentornityAnnouncementReportBridgeApi(this.announcementId, session.mentornityApiEndpoint, headers, this.strings);
    this.apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
  }
  render() {
    const listViewConfig = viewConfig$1(this.strings);
    return (index.h(index.Host, { class: "row", style: { overflow: 'hidden' } }, index.h("div", { class: "col-12" }, index.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.TableListViewConfig.decode({
    _id: 'mentornity-announcement-report',
    i18nEntryId: 'mentornity-announcement-report',
    type: viewConfig$2.AppViewType.ListViewTable,
    base: 'mentornity3',
    title: i18n.mailingReport,
    table: {
      fields: [
        new index$2.TextField('firstName', i18n.firstName),
        new index$2.TextField('lastName', i18n.lastName),
        new index$2.TextField('email', i18n.email),
        new index$2.TextField('status', i18n.status),
      ],
    },
    query: {},
    ui: tableListViewConfig.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.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.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) {
    index.registerInstance(this, hostRef);
    this.setAnnouncementRole = index.createEvent(this, "setAnnouncementRole", 7);
    this.itemsSelectedCount = 0;
    this.shownRole = 'mentor';
    this.isLoading = false;
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
      this.strings = await apiSozluk.getContent(sozlukEntries.MentornityAnnouncementWrapperI18nKey, sozlukEntries.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 } = session.getSessionDetails();
    this.api = new MentornityAnnouncementSelectUsersBridgeApi(context.organisationId, session.mentornityApiEndpoint, headers, this.organisationConfig, this.onRoleChange, this.onDataChange, this.onFetchingChange);
    this.apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.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 (index.h(index.Host, { class: "row", style: { overflow: 'hidden' } }, index.h("div", { class: "col-12" }, index.h("div", { class: "d-flex align-items-center" }, index.h("dvn-select", { class: "ml-3", value: 'mentor', onChange: (event) => this.shownRole = event.detail }, index.h("dvn-select-option", { value: 'all' }, strings.all), index.h("dvn-select-option", { value: 'mentor' }, strings.mentor), index.h("dvn-select-option", { value: 'customMentor' }, strings.customMentor), index.h("dvn-select-option", { value: 'mentee' }, strings.mentee), index.h("dvn-select-option", { value: 'customMentee' }, strings.customMentee)), this.itemsSelectedCount > 0 && index.h("p", { class: "m-0" }, index$1.SozlukApi.build(strings.selectedUsersCount, { count: this.itemsSelectedCount }))), !isCustomTarget &&
      index.h("div", { class: "ml-3", style: {
          margin: '70px auto',
          textAlign: 'center',
          color: 'var(--color-neutral)'
        } }, this.isLoading ?
        index.h("dvn-progress", { indefinite: true })
        :
          index.h("p", null, strings.selectedAllTarget))), index.h("div", { class: "col-12" }, index.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 index.getElement(this); }
};
const viewConfig = (metadata, i18n, role) => {
  const columns = {
    'email': {
      width: 300
    }
  };
  (metadata || []).forEach(data => {
    columns[data.id] = {
      width: 200
    };
  });
  return tableListViewConfig.TableListViewConfig.decode({
    _id: 'mentornity-announcement-select-users',
    i18nEntryId: 'mentornity-announcement-select-users',
    type: viewConfig$2.AppViewType.ListViewTable,
    base: 'mentornity',
    table: {
      name: role,
      fields: [
        new index$2.TextField('firstName', i18n.firstName),
        new index$2.TextField('lastName', i18n.lastName),
        new index$2.TextField('email', i18n.email),
        ...(metadata || []).map(data => new index$2.TextField(data.id, data.title))
      ],
    },
    query: {},
    ui: tableListViewConfig.TableListViewConfig.decode({
      main: {
        actionsPlacement: 'left',
        fields: [
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          { fieldId: 'email' },
          ...(metadata || []).map(data => ({ fieldId: data.id }))
        ],
        columns,
      }
    }),
  });
};

exports.dvn_stepper = DvnStepper;
exports.mentornity_announcement_form = MentornityCreateAnnouncementForm;
exports.mentornity_announcement_publish = MentornityAnnouncementPublish;
exports.mentornity_announcement_report = MentornityAnnouncementReport;
exports.mentornity_announcement_select_users = MentornityAnnouncementSelectUsers;
