import { injectNotifier } from '@dvn/alaca/global/notifier';
import { ResponsiveSize, ResponsiveUIHelper } from '@dvn/alaca/utils/ui';
import { DateField } from '@dvn/core/doldurma/src/fields/date';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { TableListViewConfig } from '@dvn/core/models/table-list-view-config';
import { AppViewType } from '@dvn/core/models/view-config';
import CalendarUtils from '@dvn/core/util/calendar';
import { SozlukApi } from '@dvn/sozluk/api';
import { Component, h, Host, Listen, Prop, State, Element } from '@stencil/core';
import { createMentornityApiInstance } from 'src/modules/mentornity-js-client';
import { Config, Organisation } from 'src/modules/mentornity-js-client/models';
import { MentornityBridgeApi } from '../../api/mentorinty-bridge-api';
import { mentornityApiEndpoint } from '../../constants/env';
import { getSessionDetails } from '../../util/session';
import { sozlukEntries } from '../sozluk-entries';
import { mentornityAnnouncementWrapperI18nDefault, MentornityAnnouncementWrapperI18nKey } from './i18n';
import { MentornityAnnouncementsWrapperBridgeApi } from './mentornity-announcements-page-wrapper-bridge-api';
export class MentornityAnnouncementsPageWrapper {
  constructor() {
    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 < 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 = 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 = h("mentornity-announcement-form", { editableAnnouncement: isAnnouncementShouldUpdate ? this.editableAnnouncement : this.currentAnnouncement, isAnnouncementShouldUpdate: isAnnouncementShouldUpdate, language: this.language });
          break;
        case 1:
          renderComponent = h("mentornity-announcement-select-users", { setSelectedItems: (data) => this.selectedItems = data, organisationConfig: this.organisationConfig, language: this.language });
          break;
        case 2:
          renderComponent = 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 (h("div", { class: `d-flex justify-content-between mx-4 my-2 ${this.isMobileUI() ? 'flex-column' : ''}` },
        h("dvn-stepper", { activeStep: this.activeStep, scale: this.isMobileUI() ? 'small' : 'large', stepOnClick: (activeIndexStep) => this.activeStep = activeIndexStep, allowToClickNextSteps: !!this.editableAnnouncement ? true : false, steps: steps }),
        h("div", null,
          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 ?
            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) &&
            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
    CalendarUtils.setTimeFormat(this.timeFormat);
    CalendarUtils.setTimeZone(this.timeZone);
    this.uiHelper = new ResponsiveUIHelper(this.el, this.onSizeChange);
    this.size = ResponsiveUIHelper.getSize(this.el.parentElement.clientWidth);
    this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
    this.strings = await this.apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    this.fetchAnnouncements();
  }
  async fetchAnnouncements() {
    const { context, headers } = getSessionDetails();
    const { organisationId } = context;
    this.api = new MentornityAnnouncementsWrapperBridgeApi(organisationId, mentornityApiEndpoint, headers, this.language, this.strings);
    this.mentornityBridgeApi = new MentornityBridgeApi(mentornityApiEndpoint, context, headers);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId)
      .then((response) => {
      this.organisationConfig = Config.decode(response);
      this.mentornityBridgeApi.organisationConfig = 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 h("div", null,
        h("dvn-progress", { indefinite: true, tint: "primary" }));
    }
    const { strings } = this;
    const listViewConfig = viewConfig(this.strings);
    const renderCurrentStepContent = this.getCurrentContent();
    return (h(Host, { class: "d-flex flex-grow-1", style: { overflow: 'hidden' } },
      h("mentornity-root-wrapper", { class: "d-flex pl-3 pr-3" },
        h("div", { class: "d-flex mt-3 align-items-center mb-4" },
          h("dvn-button", { tint: "primary", leaned: true, onClick: () => {
              this.activeStep = 0;
              this.showCreateAnnouncementDialog = true;
              this.editableAnnouncement = undefined;
              this.currentAnnouncement = undefined;
            } }, strings.createAnnouncement),
          h("p", { class: "mb-0 ml-3" }, strings.createAnnouncementDescription)),
        h("dvn-app-view-list-view-table", { key: this.randomId, apiData: this.api, apiSozluk: this.apiSozluk, view: listViewConfig }),
        this.showReportDialog &&
          h("dvn-dialog", { shown: this.showReportDialog, onDismiss: () => {
              this.showReportDialog = false;
            }, width: "fit-content" },
            h("mentornity-announcement-report", { announcementId: (_a = this.currentAnnouncement) === null || _a === void 0 ? void 0 : _a._id, language: this.language })),
        h("dvn-dialog", { title: strings.areYouSure, shown: this.openSendEmailsControlDialog },
          SozlukApi.build(strings.sendToUsersControl, { count: (_b = this.selectedItems) === null || _b === void 0 ? void 0 : _b.length }),
          h("div", { slot: "actions" },
            h("dvn-button", { view: "flat", onClick: () => {
                this.showCreateAnnouncementDialog = false;
                this.openSendEmailsControlDialog = false;
                this.editableAnnouncement = undefined;
                this.currentAnnouncement = undefined;
              } }, strings.cancel),
            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))),
        h("dvn-dialog", { shown: this.showCreateAnnouncementDialog, onDismiss: () => {
            this.showCreateAnnouncementDialog = false;
            this.editableAnnouncement = undefined;
            this.currentAnnouncement = undefined;
          }, width: '1100px' }, this.showCreateAnnouncementDialog &&
          h("div", null,
            this.renderSteps(),
            renderCurrentStepContent)),
        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 &&
            h("div", { class: "d-flex justify-content-end mb-4" },
              h("dvn-button", { view: 'outline', leaned: true, onClick: () => this.previewAsUserHandler() },
                h("div", { class: "d-flex align-items-center" },
                  h("dvn-icon", { iconName: "uil uil-edit-alt", scale: "large" }),
                  strings.goBackToEditing))),
          h("dvn-markdown", { content: this.formatAnnouncementContent(((_d = this.showAnnouncementPreview) === null || _d === void 0 ? void 0 : _d.content) || '') })))));
  }
  static get is() { return "mentornity-announcements-page-wrapper"; }
  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
    },
    "notifier": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Notifier",
        "resolved": "Notifier",
        "references": {
          "Notifier": {
            "location": "import",
            "path": "@dvn/alaca/global/notifier/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "timeFormat": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "time-format",
      "reflect": false
    },
    "timeZone": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "time-zone",
      "reflect": false
    }
  }; }
  static get states() { return {
    "size": {},
    "mentornityApi": {},
    "organisationConfig": {},
    "mentornityBridgeApi": {},
    "showCreateAnnouncementDialog": {},
    "showAnnouncementPreview": {},
    "showReportDialog": {},
    "isPreview": {},
    "editableAnnouncement": {},
    "activeStep": {},
    "selectedItems": {},
    "announcements": {},
    "isAnnouncementsLoading": {},
    "openSendEmailsControlDialog": {},
    "isSaving": {},
    "isClosing": {},
    "currentAnnouncement": {},
    "currentAnnouncementTarget": {},
    "strings": {},
    "randomId": {}
  }; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "updateStatusAnnouncement",
      "method": "updateStatusAnnouncementEvent",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "showPreview",
      "method": "showPreviewDialogHandler",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "previewAsUser",
      "method": "previewAsUserHandler",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "openAnnouncementReport",
      "method": "openAnnouncementReport",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "openSelectUsersDialog",
      "method": "openSelectUsersDialog",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "showErrorMessage",
      "method": "showErrorMessage",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "duplicateAnnouncement",
      "method": "duplicateAnnouncement",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "sendEmails",
      "method": "sendEmails",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "getCurrentAnnouncement",
      "method": "getCurrentAnnouncement",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "setAnnouncementRole",
      "method": "setAnnouncementRole",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "editAnnouncement",
      "method": "editAnnoncement",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "deleteAnnouncement",
      "method": "deleteAnnouncement",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
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.decode({
    _id: 'mentornity-announcements-page-wrapper',
    i18nEntryId: 'mentornity-announcements-page-wrapper',
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    title: i18n.announcements,
    table: {
      fields: [
        new DateField('createdAt', i18n.createdDate).setDateFormat('DD MMM YYYY'),
        new TextField('title', i18n.title),
        new TextField('recipients', i18n.recipients),
        new TextField('status', i18n.publishedOnPlatform),
        new TextField('mailingActions', i18n.mailing)
      ],
    },
    query: {},
    ui: 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,
      }
    }),
  });
};
injectNotifier(MentornityAnnouncementsPageWrapper);
