"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const ewsJavascriptApi = require("ews-javascript-api");
const index = require("./i18n-Bs8xJzoY.cjs");
var ExchangeAuthentication = /* @__PURE__ */ ((ExchangeAuthentication2) => {
  ExchangeAuthentication2[ExchangeAuthentication2["STANDARD"] = 0] = "STANDARD";
  ExchangeAuthentication2[ExchangeAuthentication2["NTLM"] = 1] = "NTLM";
  return ExchangeAuthentication2;
})(ExchangeAuthentication || {});
class ExchangeCalendarService {
  constructor(credential) {
    this.integrationName = "";
    this.integrationName = "exchange_calendar";
    this.log = index.logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
    this.payload = JSON.parse(
      index.symmetricDecrypt(credential.key?.toString() || "", process.env.CALENDSO_ENCRYPTION_KEY || "")
    );
  }
  async createEvent(event) {
    const appointment = new ewsJavascriptApi.Appointment(await this.getExchangeService());
    appointment.Subject = event.title;
    appointment.Start = ewsJavascriptApi.DateTime.Parse(event.startTime);
    appointment.End = ewsJavascriptApi.DateTime.Parse(event.endTime);
    appointment.Location = event.location || "";
    appointment.Body = new ewsJavascriptApi.MessageBody(event.description || "");
    event.attendees.forEach((attendee) => {
      appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(attendee.email));
    });
    if (event.team?.members) {
      event.team.members.forEach((member) => {
        appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(member.email));
      });
    }
    return appointment.Save(ewsJavascriptApi.SendInvitationsMode.SendToAllAndSaveCopy).then(() => {
      return {
        uid: appointment.Id.UniqueId,
        id: appointment.Id.UniqueId,
        password: "",
        type: "",
        url: "",
        additionalInfo: {}
      };
    }).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async updateEvent(uid, event) {
    const appointment = await ewsJavascriptApi.Appointment.Bind(await this.getExchangeService(), new ewsJavascriptApi.ItemId(uid));
    appointment.Subject = event.title;
    appointment.Start = ewsJavascriptApi.DateTime.Parse(event.startTime);
    appointment.End = ewsJavascriptApi.DateTime.Parse(event.endTime);
    appointment.Location = event.location || "";
    appointment.Body = new ewsJavascriptApi.MessageBody(event.description || "");
    event.attendees.forEach((attendee) => {
      appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(attendee.email));
    });
    if (event.team?.members) {
      event.team.members.forEach((member) => {
        appointment.RequiredAttendees.Add(new ewsJavascriptApi.Attendee(member.email));
      });
    }
    return appointment.Update(
      ewsJavascriptApi.ConflictResolutionMode.AlwaysOverwrite,
      ewsJavascriptApi.SendInvitationsOrCancellationsMode.SendToChangedAndSaveCopy
    ).then(() => {
      return {
        uid: appointment.Id.UniqueId,
        id: appointment.Id.UniqueId,
        password: "",
        type: "",
        url: "",
        additionalInfo: {}
      };
    }).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async deleteEvent(uid) {
    const appointment = await ewsJavascriptApi.Appointment.Bind(await this.getExchangeService(), new ewsJavascriptApi.ItemId(uid));
    return appointment.Delete(ewsJavascriptApi.DeleteMode.MoveToDeletedItems).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async getAvailability(dateFrom, dateTo, selectedCalendars) {
    const calendars = await this.listCalendars();
    const promises = calendars.filter((lcal) => selectedCalendars.some((rcal) => lcal.externalId == rcal.externalId)).map(async (calendar) => {
      return (await this.getExchangeService()).FindAppointments(
        new ewsJavascriptApi.FolderId(calendar.externalId),
        new ewsJavascriptApi.CalendarView(ewsJavascriptApi.DateTime.Parse(dateFrom), ewsJavascriptApi.DateTime.Parse(dateTo))
      ).then((results) => {
        return results.Items.filter((appointment) => {
          return appointment.LegacyFreeBusyStatus != ewsJavascriptApi.LegacyFreeBusyStatus.Free;
        }).map((appointment) => {
          return {
            start: new Date(appointment.Start.ToISOString()),
            end: new Date(appointment.End.ToISOString())
          };
        });
      }).catch((reason) => {
        this.log.error(reason);
        throw reason;
      });
    });
    return Promise.all(promises).then((x) => x.flat());
  }
  async listCalendars() {
    const service = await this.getExchangeService();
    const view = new ewsJavascriptApi.FolderView(1e3);
    view.PropertySet = new ewsJavascriptApi.PropertySet(ewsJavascriptApi.BasePropertySet.IdOnly);
    view.PropertySet.Add(ewsJavascriptApi.FolderSchema.ParentFolderId);
    view.PropertySet.Add(ewsJavascriptApi.FolderSchema.DisplayName);
    view.PropertySet.Add(ewsJavascriptApi.FolderSchema.ChildFolderCount);
    view.Traversal = ewsJavascriptApi.FolderTraversal.Deep;
    const deletedItemsFolder = await ewsJavascriptApi.Folder.Bind(service, ewsJavascriptApi.WellKnownFolderName.DeletedItems);
    const searchFilterCollection = new ewsJavascriptApi.SearchFilter.SearchFilterCollection(ewsJavascriptApi.LogicalOperator.And);
    searchFilterCollection.Add(new ewsJavascriptApi.SearchFilter.IsEqualTo(ewsJavascriptApi.FolderSchema.FolderClass, "IPF.Appointment"));
    return service.FindFolders(ewsJavascriptApi.WellKnownFolderName.MsgFolderRoot, searchFilterCollection, view).then((res) => {
      return res.Folders.filter((folder) => {
        return folder.ParentFolderId.UniqueId != deletedItemsFolder.Id.UniqueId;
      }).map((folder) => {
        return {
          externalId: folder.Id.UniqueId,
          name: folder.DisplayName ?? "",
          primary: folder.ChildFolderCount > 0,
          integration: this.integrationName
        };
      });
    }).catch((reason) => {
      this.log.error(reason);
      throw reason;
    });
  }
  async getExchangeService() {
    const service = new ewsJavascriptApi.ExchangeService(this.payload.exchangeVersion);
    service.Credentials = new ewsJavascriptApi.WebCredentials(this.payload.username, this.payload.password);
    service.Url = new ewsJavascriptApi.Uri(this.payload.url);
    if (this.payload.authenticationMethod === ExchangeAuthentication.NTLM) {
      const { XhrApi } = await import("@ewsjs/xhr");
      const xhr = new XhrApi({
        rejectUnauthorized: false
      }).useNtlmAuthentication(this.payload.username, this.payload.password);
      service.XHRApi = xhr;
    }
    return service;
  }
}
exports.default = ExchangeCalendarService;
