'use strict';

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

const index = require('./index-1141a245.js');
const index$3 = require('./index-f41ad23a.js');
const ui = require('./ui-924b3658.js');
require('./index-2eea69a0.js');
const index$2 = require('./index-61f9621a.js');
const tableListViewConfig = require('./table-list-view-config-a7907d79.js');
const viewConfig$1 = require('./view-config-52c16db0.js');
const calendar = require('./calendar-e4b7baeb.js');
const index$1 = require('./index-a2e99c85.js');
const apiBase = require('./apiBase-6c66ff1b.js');
require('./data-transfer-field-e8417d5f.js');
require('./filter-d5040f65.js');
const session = require('./session-f588baa3.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-b1eaa56d.js');
const sozlukEntries = require('./sozluk-entries-3b9686e7.js');
const dataModel = require('./data-model-01c368bc.js');
const date = require('./date-a24d7714.js');
require('./state-tunnel-786a62ce.js');
require('./FieldGenerator-279a646b.js');
require('./BaseField-381327a9.js');
require('./table-config-969d3038.js');
require('./FieldModelGenerator-d61f01d4.js');
require('./reference-field-1239b0c3.js');
require('./index-0783d14f.js');
require('./index-9d3d3d15.js');
require('./index-9fd84b93.js');
require('./index-b776fc14.js');
require('./_commonjsHelpers-206db00d.js');
require('./moment-7a3433f2.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('./index-b7855ed6.js');
require('./attachment-a0cdf203.js');
require('./CalendarConfig-998f742e.js');
require('./i18n-0bcf144d.js');
require('./i18n-77d45414.js');

class MentornityAnnouncementsWrapperBridgeApi {
  constructor(organisationId, endpoint, headers, language, strings) {
    this.client = new apiBase.APIBase(endpoint, headers);
    this.organisationId = organisationId;
    this.language = language;
    this.strings = strings;
  }
  addAuthInterceptor(_token) {
    // console.log('MBA.addAuthInterceptor', token);
  }
  // region DataApi
  get(_collection, _id, _query) {
    return undefined;
  }
  query() {
    return new Promise((resolve => {
      this.client.get(`organisations/${this.organisationId}/announcements`).then(response => {
        resolve({
          results: response.results.map((item) => dataModel.DataModel.decode(Object.assign(Object.assign({ _id: item._id }, (item || {})), { createdAt: item.createdAt * 1000, recipients: this.strings[item.target], status: item.status, 
            // inserted for sub components
            language: this.language }))),
          meta: {
            total: response.results.length,
          }
        });
      }).catch(e => {
        console.log(e);
      });
    }));
  }
  update(_collection, _id, _body) {
    return undefined;
  }
}

const MentornityAnnouncementsPageWrapper = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.showCreateAnnouncementDialog = false;
    this.showAnnouncementPreview = undefined;
    this.showReportDialog = false;
    this.isPreview = false;
    this.activeStep = 0;
    this.selectedItems = [];
    this.isAnnouncementsLoading = true;
    this.openSendEmailsControlDialog = false;
    this.isSaving = false;
    this.isClosing = false;
    this.formatAnnouncementContent = (content) => {
      content = content.replace(/&lt;/g, '<');
      content = content.replace(/&gt;/g, '>');
      return content;
    };
    this.onSizeChange = (size) => {
      this.size = size;
    };
    this.isMobileUI = () => this.size < ui.ResponsiveSize.Small;
    this.updateStatusAnnouncement = (announcement) => {
      var _a, _b;
      const body = {
        status: announcement.status === 'published' ? 'unpublished' : 'published'
      };
      this.mentornityApi.updateAnouncement(announcement._id, body)
        .then(() => this.notifier.congratulate(this.strings.announcementAreUpdated))
        .catch(() => this.notifier.alert(this.strings.savingFailed));
      (_b = (_a = this.el.querySelector(`dvn-app-view-list-view-table`)) === null || _a === void 0 ? void 0 : _a.invalidate) === null || _b === void 0 ? void 0 : _b.call(_a);
    };
    this.updateAnnouncement = async (announcement, goNextStep = false) => {
      const announcementForm = announcement;
      const usersId = [];
      this.selectedItems.forEach(user => usersId.push({ userId: user._id }));
      const body = {
        title: announcementForm.title,
        content: announcementForm.content,
        target: announcementForm.target,
        targetList: usersId
      };
      try {
        await this.mentornityApi.updateAnouncement(announcementForm._id, body);
        this.notifier.congratulate(this.strings.announcementAreUpdated);
        if (goNextStep)
          this.activeStep += 1;
      }
      catch (error) {
        this.notifier.alert(this.strings.savingFailed);
      }
    };
    this.createAnnouncement = async (sendNotify = false, goNextStep = false) => {
      var _a, _b, _c;
      let organisation = await this.mentornityApi.getOrganisation(this.organisationConfig.organisation._id);
      organisation = session.Organisation.decode(organisation);
      const body = {
        title: this.currentAnnouncement.title,
        content: this.currentAnnouncement.content,
        target: 'all',
        status: 'unpublished',
        organisation: organisation.ref(),
        sendEmail: false
      };
      try {
        await this.mentornityApi.createAnouncement(body);
        await this.fetchAnnouncements();
        (_b = (_a = this.el.querySelector(`dvn-app-view-list-view-table`)) === null || _a === void 0 ? void 0 : _a.invalidate) === null || _b === void 0 ? void 0 : _b.call(_a);
        if (sendNotify)
          this.notifier.congratulate(this.strings.announcementAreCreated);
        if (goNextStep)
          this.activeStep += 1;
      }
      catch (error) {
        if (sendNotify)
          this.showErrorMessage((_c = error.data) === null || _c === void 0 ? void 0 : _c.message);
      }
    };
    this.sendEmailsToSelectedUsers = async () => {
      var _a, _b, _c;
      const usersId = [];
      this.selectedItems.forEach(user => usersId.push({ userId: user._id }));
      try {
        await this.mentornityApi.sendEmailsForAnnouncement(this.currentAnnouncement._id, usersId, this.currentAnnouncement.target);
        this.showCreateAnnouncementDialog = false;
        this.openSendEmailsControlDialog = false;
        this.currentAnnouncement = undefined;
        (_b = (_a = this.el.querySelector(`dvn-app-view-list-view-table`)) === null || _a === void 0 ? void 0 : _a.invalidate) === null || _b === void 0 ? void 0 : _b.call(_a);
      }
      catch (error) {
        this.showErrorMessage((_c = error.data) === null || _c === void 0 ? void 0 : _c.message);
      }
    };
    this.makeActionForCurrentStep = async () => {
      var _a, _b;
      switch (this.activeStep) {
        case 0:
          if (!!this.editableAnnouncement) {
            await this.updateAnnouncement(this.editableAnnouncement, true);
            this.currentAnnouncement = this.editableAnnouncement;
          }
          else {
            await this.createAnnouncement(true, true);
            // get the announcement that we created
            this.currentAnnouncement = this.announcements[0];
          }
          break;
        case 1:
          const hasSelectedUsers = this.selectedItems.length > 0;
          if (hasSelectedUsers) {
            this.currentAnnouncement.target = this.currentAnnouncementTarget || this.currentAnnouncement.target;
            await this.updateAnnouncement(this.currentAnnouncement);
            (_b = (_a = this.el.querySelector(`dvn-app-view-list-view-table`)) === null || _a === void 0 ? void 0 : _a.invalidate) === null || _b === void 0 ? void 0 : _b.call(_a);
            this.activeStep += 1;
          }
          else {
            this.showErrorMessage(this.strings.youHaveSelectUsers);
          }
          break;
      }
    };
    this.getCurrentContent = () => {
      let renderComponent = null;
      switch (this.activeStep) {
        case 0:
          const isAnnouncementShouldUpdate = !!this.editableAnnouncement;
          renderComponent = index.h("mentornity-announcement-form", { editableAnnouncement: isAnnouncementShouldUpdate ? this.editableAnnouncement : this.currentAnnouncement, isAnnouncementShouldUpdate: isAnnouncementShouldUpdate, language: this.language });
          break;
        case 1:
          renderComponent = index.h("mentornity-announcement-select-users", { setSelectedItems: (data) => this.selectedItems = data, organisationConfig: this.organisationConfig, language: this.language });
          break;
        case 2:
          renderComponent = index.h("mentornity-announcement-publish", { language: this.language, selectedUsers: this.selectedItems, announcement: this.currentAnnouncement, isLoading: this.isSaving });
          break;
      }
      return renderComponent;
    };
    this.renderSteps = () => {
      const { strings } = this;
      const steps = [
        {
          label: strings.announcement
        },
        {
          label: strings.recipients
        },
        {
          label: strings.publish
        }
      ];
      return (index.h("div", { class: `d-flex justify-content-between mx-4 my-2 ${this.isMobileUI() ? 'flex-column' : ''}` }, index.h("dvn-stepper", { activeStep: this.activeStep, scale: this.isMobileUI() ? 'small' : 'large', stepOnClick: (activeIndexStep) => this.activeStep = activeIndexStep, allowToClickNextSteps: !!this.editableAnnouncement ? true : false, steps: steps }), index.h("div", null, index.h("dvn-button", { tint: "primary", view: "flat", leaned: true, disabled: this.isSaving || this.isClosing, onClick: () => {
          this.showCreateAnnouncementDialog = false;
          this.currentAnnouncement = undefined;
        } }, strings.close), this.activeStep === 0 ?
        index.h("dvn-button", { tint: "primary", view: "flat", leaned: true, disabled: this.isClosing || this.isSaving, progressing: this.isClosing, onClick: async () => {
            this.isClosing = true;
            if (!!this.editableAnnouncement) {
              await this.updateAnnouncement(this.editableAnnouncement);
            }
            else {
              await this.createAnnouncement(true);
            }
            this.showCreateAnnouncementDialog = false;
            this.isClosing = false;
          } }, !!this.editableAnnouncement ? strings.update : strings.create, " & ", strings.close)
        :
          '', !(this.activeStep === 2) &&
        index.h("dvn-button", { tint: "primary", leaned: true, onClick: async () => {
            this.isSaving = true;
            await this.makeActionForCurrentStep();
            this.isSaving = false;
          }, progressing: this.isSaving, disabled: this.isClosing || this.isSaving }, !!this.editableAnnouncement ? strings.update : this.activeStep === 1 ? strings.save : strings.create, " & ", strings.next))));
    };
  }
  async componentWillLoad() {
    // set user's locale and time zone
    calendar.CalendarUtils.setTimeFormat(this.timeFormat);
    calendar.CalendarUtils.setTimeZone(this.timeZone);
    this.uiHelper = new ui.ResponsiveUIHelper(this.el, this.onSizeChange);
    this.size = ui.ResponsiveUIHelper.getSize(this.el.parentElement.clientWidth);
    this.apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
    this.strings = await this.apiSozluk.getContent(sozlukEntries.MentornityAnnouncementWrapperI18nKey, sozlukEntries.mentornityAnnouncementWrapperI18nDefault);
    this.fetchAnnouncements();
  }
  async fetchAnnouncements() {
    const { context, headers } = session.getSessionDetails();
    const { organisationId } = context;
    this.api = new MentornityAnnouncementsWrapperBridgeApi(organisationId, session.mentornityApiEndpoint, headers, this.language, this.strings);
    this.mentornityBridgeApi = new mentorintyBridgeApi.MentornityBridgeApi(session.mentornityApiEndpoint, context, headers);
    const mentornityApi = session.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId)
      .then((response) => {
      this.organisationConfig = session.Config.decode(response);
      this.mentornityBridgeApi.organisationConfig = session.Config.decode(response);
    });
    this.mentornityApi = mentornityApi;
    // Fetch announcements from api
    this.announcements = await mentornityApi.getAnnouncements(organisationId);
    this.isAnnouncementsLoading = false;
  }
  updateStatusAnnouncementEvent(event) {
    const announcement = event === null || event === void 0 ? void 0 : event.detail;
    this.updateStatusAnnouncement(announcement);
  }
  showPreviewDialogHandler(event) {
    const announcementForm = event === null || event === void 0 ? void 0 : event.detail;
    this.showAnnouncementPreview = announcementForm;
    this.isPreview = true;
  }
  previewAsUserHandler(event) {
    const announcementForm = event === null || event === void 0 ? void 0 : event.detail;
    this.showCreateAnnouncementDialog = !this.showCreateAnnouncementDialog;
    this.showAnnouncementPreview = announcementForm;
  }
  async openAnnouncementReport(event) {
    const announcementForm = event === null || event === void 0 ? void 0 : event.detail;
    try {
      this.showCreateAnnouncementDialog = false;
      this.showReportDialog = true;
      this.currentAnnouncement = announcementForm;
    }
    catch (error) {
      this.notifier.alert(this.strings.savingFailed);
    }
  }
  openSelectUsersDialog(event) {
    const announcementForm = event === null || event === void 0 ? void 0 : event.detail;
    this.activeStep = 1;
    this.showCreateAnnouncementDialog = true;
    this.currentAnnouncement = announcementForm;
    this.editableAnnouncement = announcementForm;
    this.selectedItems = [];
  }
  showErrorMessage(message) {
    const shownMessage = message.detail ? message.detail : message;
    this.notifier.alert(shownMessage);
  }
  duplicateAnnouncement(event) {
    const announcementForm = event === null || event === void 0 ? void 0 : event.detail;
    this.currentAnnouncement = announcementForm;
    this.activeStep = 0;
    this.showCreateAnnouncementDialog = true;
  }
  async sendEmails() {
    this.showCreateAnnouncementDialog = false;
    this.openSendEmailsControlDialog = true;
  }
  getCurrentAnnouncement(event) {
    const announcementForm = event === null || event === void 0 ? void 0 : event.detail;
    this.currentAnnouncement = announcementForm;
  }
  setAnnouncementRole(event) {
    const target = event === null || event === void 0 ? void 0 : event.detail;
    this.currentAnnouncementTarget = target;
  }
  editAnnoncement(event) {
    const announcementForm = event === null || event === void 0 ? void 0 : event.detail;
    this.activeStep = 0;
    this.editableAnnouncement = announcementForm;
    this.showCreateAnnouncementDialog = true;
  }
  async deleteAnnouncement(event) {
    const announcementId = event === null || event === void 0 ? void 0 : event.detail;
    try {
      await this.mentornityApi.deleteAnouncement(announcementId);
      this.randomId = announcementId;
      this.notifier.congratulate(this.strings.announcementAreDeleted);
    }
    catch (error) {
      this.notifier.alert(this.strings.savingFailed);
    }
  }
  render() {
    var _a, _b, _c, _d;
    if (this.isAnnouncementsLoading) {
      return index.h("div", null, index.h("dvn-progress", { indefinite: true, tint: "primary" }));
    }
    const { strings } = this;
    const listViewConfig = viewConfig(this.strings);
    const renderCurrentStepContent = this.getCurrentContent();
    return (index.h(index.Host, { class: "d-flex flex-grow-1", style: { overflow: 'hidden' } }, index.h("mentornity-root-wrapper", { class: "d-flex pl-3 pr-3" }, index.h("div", { class: "d-flex mt-3 align-items-center mb-4" }, index.h("dvn-button", { tint: "primary", leaned: true, onClick: () => {
        this.activeStep = 0;
        this.showCreateAnnouncementDialog = true;
        this.editableAnnouncement = undefined;
        this.currentAnnouncement = undefined;
      } }, strings.createAnnouncement), index.h("p", { class: "mb-0 ml-3" }, strings.createAnnouncementDescription)), index.h("dvn-app-view-list-view-table", { key: this.randomId, apiData: this.api, apiSozluk: this.apiSozluk, view: listViewConfig }), this.showReportDialog &&
      index.h("dvn-dialog", { shown: this.showReportDialog, onDismiss: () => {
          this.showReportDialog = false;
        }, width: "fit-content" }, index.h("mentornity-announcement-report", { announcementId: (_a = this.currentAnnouncement) === null || _a === void 0 ? void 0 : _a._id, language: this.language })), index.h("dvn-dialog", { title: strings.areYouSure, shown: this.openSendEmailsControlDialog }, index$1.SozlukApi.build(strings.sendToUsersControl, { count: (_b = this.selectedItems) === null || _b === void 0 ? void 0 : _b.length }), index.h("div", { slot: "actions" }, index.h("dvn-button", { view: "flat", onClick: () => {
        this.showCreateAnnouncementDialog = false;
        this.openSendEmailsControlDialog = false;
        this.editableAnnouncement = undefined;
        this.currentAnnouncement = undefined;
      } }, strings.cancel), index.h("dvn-button", { tint: "primary", view: "flat", disabled: this.isSaving, progressing: this.isSaving, onClick: async () => {
        this.isSaving = true;
        await this.sendEmailsToSelectedUsers();
        this.isSaving = false;
      } }, strings.yes))), index.h("dvn-dialog", { shown: this.showCreateAnnouncementDialog, onDismiss: () => {
        this.showCreateAnnouncementDialog = false;
        this.editableAnnouncement = undefined;
        this.currentAnnouncement = undefined;
      }, width: '1100px' }, this.showCreateAnnouncementDialog &&
      index.h("div", null, this.renderSteps(), renderCurrentStepContent)), index.h("dvn-dialog", { title: (_c = this.showAnnouncementPreview) === null || _c === void 0 ? void 0 : _c.title, shown: !!this.showAnnouncementPreview, separateHeader: true, onDismiss: () => {
        this.showAnnouncementPreview = undefined;
        this.isPreview = false;
      } }, !this.isPreview &&
      index.h("div", { class: "d-flex justify-content-end mb-4" }, index.h("dvn-button", { view: 'outline', leaned: true, onClick: () => this.previewAsUserHandler() }, index.h("div", { class: "d-flex align-items-center" }, index.h("dvn-icon", { iconName: "uil uil-edit-alt", scale: "large" }), strings.goBackToEditing))), index.h("dvn-markdown", { content: this.formatAnnouncementContent(((_d = this.showAnnouncementPreview) === null || _d === void 0 ? void 0 : _d.content) || '') })))));
  }
  get el() { return index.getElement(this); }
};
const viewConfig = (i18n) => {
  const columns = {
    'title': {
      width: 200
    },
    'createdAt': {
      width: 150
    },
    'actions': {
      width: 50
    },
    'recipients': {
      width: 200
    },
    'status': {
      width: 300
    },
    'mailingActions': {
      width: 500
    }
  };
  return tableListViewConfig.TableListViewConfig.decode({
    _id: 'mentornity-announcements-page-wrapper',
    i18nEntryId: 'mentornity-announcements-page-wrapper',
    type: viewConfig$1.AppViewType.ListViewTable,
    base: 'mentornity',
    title: i18n.announcements,
    table: {
      fields: [
        new date.DateField('createdAt', i18n.createdDate).setDateFormat('DD MMM YYYY'),
        new index$2.TextField('title', i18n.title),
        new index$2.TextField('recipients', i18n.recipients),
        new index$2.TextField('status', i18n.publishedOnPlatform),
        new index$2.TextField('mailingActions', i18n.mailing)
      ],
    },
    query: {},
    ui: tableListViewConfig.TableListViewConfig.decode({
      main: {
        actionsPlacement: 'left',
        fields: [
          { fieldDisplay: { id: 'actions' }, componentTag: 'mentornity-announcements-dropdown-menu' },
          { fieldId: 'title' },
          { fieldId: 'createdAt' },
          { fieldId: 'recipients' },
          { fieldId: 'status', componentTag: 'mentornity-announcements-status-switch' },
          { fieldId: 'mailingActions', componentTag: 'mentornity-announcements-mailing-report' },
        ],
        columns,
      }
    }),
  });
};
index$3.injectNotifier(MentornityAnnouncementsPageWrapper);

exports.mentornity_announcements_page_wrapper = MentornityAnnouncementsPageWrapper;
