'use strict';

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

const index = require('./index-1ee80297.js');
const ui = require('./ui-2403d3b4.js');
const index$2 = require('./index-521d07b9.js');
const index$3 = require('./index-a77c3004.js');
const InterceptorHandler = require('./InterceptorHandler-09a1e84b.js');
const string = require('./string-de672b69.js');
const User = require('./User-286a0714.js');
const dateUtils = require('./date-utils-86cd43eb.js');
const Availability = require('./Availability-bea8045d.js');
require('./data-model-c51de090.js');
require('./index-42baafa9.js');
require('./index-9e7c4ca0.js');
const index$1 = require('./index-1f95aafc.js');
const timeZones = require('./time-zones-5b212929.js');
const calendar = require('./calendar-e830b67f.js');
const index$4 = require('./index-b2910095.js');
const i18n = require('./i18n-0bdc9383.js');
require('./BaseField-d019ade6.js');
require('./date-25b104f6.js');
require('./_commonjsHelpers-206db00d.js');
require('./moment-d48a0164.js');
require('./i18n-a8cc9ef1.js');

class VisibilityHandler extends InterceptorHandler.InterceptorHandler {
  run(context, values, field, value, boundField) {
    return { value: values[boundField.id], visible: this.shouldShow(context, values, field, value) };
  }
}

function doesSatisfyRule(rule, data) {
  if (!rule || !data) {
    return true;
  }
  if (rule.type === 'group') {
    if (!rule.rules || rule.rules.length === 0) {
      return true;
    }
    for (let i = 0; i < (rule.rules || []).length; i++) {
      const satisfies = doesSatisfyRule(rule.rules[i], data);
      if (satisfies && rule.operator === 'or') {
        // return true if any rule satisfies in 'or'
        return true;
      }
      else if (!satisfies && rule.operator === 'and') {
        // return false if any rule doesn't satisfy in 'and'
        return false;
      }
      else if (satisfies && rule.operator === 'and' && i === rule.rules.length - 1) {
        // return true if the last rule satisfies in 'and'
        return true;
      }
    }
  }
  else if (rule.type === 'condition') {
    const { condition, value, key } = rule;
    if (!condition || !key) {
      // condition is not valid
      return false;
    }
    switch (condition) {
      case 'eq': {
        switch (typeof data[key]) {
          case 'boolean': {
            // tslint:disable-next-line
            return data[key] == value;
          }
          case 'number': {
            // tslint:disable-next-line
            return data[key] == value;
          }
          case 'string': {
            // tslint:disable-next-line
            return (data[key] || '').trim() == (value || '').trim();
          }
        }
        return false;
      }
      case 'ne': {
        switch (typeof data[key]) {
          case 'boolean': {
            // tslint:disable-next-line
            return data[key] != value;
          }
          case 'number': {
            // tslint:disable-next-line
            return data[key] != value;
          }
          case 'string': {
            // tslint:disable-next-line
            return (data[key] || '').trim() != (value || '').trim();
          }
        }
        return false;
      }
    }
  }
  return false;
}

class ConcealerConditional extends InterceptorHandler.InterceptorConfig {
  constructor(rule) {
    super('concealerGenericRule');
    this.rule = rule;
  }
}
ConcealerConditional.id = 'concealerGenericRule';
class ConcealerGenericRuleHandler extends VisibilityHandler {
  constructor(config) {
    super();
    this.config = config;
  }
  shouldShow(_context, values, _field, _value) {
    return doesSatisfyRule(this.config.rule, values);
  }
}
InterceptorHandler.registerInterceptor(ConcealerConditional.id, (config) => new ConcealerGenericRuleHandler(config));

class Rule {
  constructor(type) {
    this.type = type;
  }
}

class Equal extends Rule {
  constructor(key, value) {
    super('condition');
    this.condition = 'eq';
    this.key = key;
    this.value = value;
  }
}

const MAX_MONTH_FOR_RECURRENCE = 3;
const lastday = (date) => {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
};
/**
 * Generates the availabilities from the raw availability list by using their recurrence.
 * Recurring availabilities are populated for every week/month until the maxMonthForRecurrence is reached.
 * @param availabilities
 * @param maxMonthForRecurrence
 * @param startDate used for calculating the end month
 */
const generateAvailabilities = (availabilities, maxMonthForRecurrence = MAX_MONTH_FOR_RECURRENCE, startDate = new Date()) => {
  const maxDate = dateUtils.iterateMonth(startDate, maxMonthForRecurrence);
  maxDate.setDate(lastday(maxDate)); // last day is the end of the iterated month
  const now = new Date();
  const allAvailabilities = [];
  availabilities.forEach(availability => {
    if (availability.recurrence === 'weekly') {
      let baseStartDate = new Date(availability.startDate);
      let baseEndDate = new Date(availability.endDate);
      while (dateUtils.isBefore(baseStartDate, maxDate)) {
        allAvailabilities.push(Availability.Availability.decode(Object.assign(Object.assign({}, availability), { startDate: baseStartDate.toISOString(), endDate: baseEndDate.toISOString() })));
        baseStartDate = dateUtils.iterateWeek(baseStartDate, 1);
        baseEndDate = dateUtils.iterateWeek(baseEndDate, 1);
      }
    }
    else if (new Date(availability.endDate) >= now) {
      // single
      allAvailabilities.push(availability);
    }
  });
  return allAvailabilities;
};
/**
 * Returns the earliest start time and latest end time of the given availabilities.
 * @param availabilities
 */
const getTimeFrameOfAvailabilities = (availabilities) => {
  let startDate;
  let endDate;
  availabilities.forEach(availability => {
    if (!startDate || dateUtils.isBefore(new Date(availability.startDate), startDate)) {
      startDate = new Date(availability.startDate);
    }
    if (!endDate || dateUtils.isAfter(new Date(availability.endDate), endDate)) {
      endDate = new Date(availability.endDate);
    }
  });
  return { startDate, endDate };
};
const generateSlotsForAvailabilities = (availabilities = [], unavailabilitiesOfCurrentUser, unavailabilitiesOfOtherUser) => {
  const timeSlots = [];
  availabilities.forEach(availability => {
    const slots = generateSlotsForAvailability(availability);
    slots.forEach(slot => {
      if (new Date(slot.start) < new Date()) {
        return;
      }
      let hasIntersection = false;
      for (let i = 0; i < unavailabilitiesOfOtherUser.length; i++) {
        const unavailability = unavailabilitiesOfOtherUser[i];
        if (doTimesIntersect(slot.start, slot.end, new Date(unavailability.startDate), new Date(unavailability.endDate))) {
          hasIntersection = true;
          break;
        }
      }
      if (hasIntersection) {
        return;
      }
      for (let i = 0; i < unavailabilitiesOfCurrentUser.length; i++) {
        const unavailability = unavailabilitiesOfCurrentUser[i];
        if (doTimesIntersect(new Date(slot.start), new Date(slot.end), new Date(unavailability.startDate), new Date(unavailability.endDate))) {
          slot.sessionUserConflict = unavailability.reason;
          break;
        }
      }
      timeSlots.push(slot);
    });
  });
  return timeSlots;
};
const doTimesIntersect = (start1, end1, start2, end2) => {
  if (dateUtils.isEqual(start1, start2) || dateUtils.isEqual(end1, end2)) {
    return true;
  }
  // s1    e1
  //    s2    e2
  if (dateUtils.isBefore(start1, start2) && dateUtils.isBefore(start2, end1)) {
    return true;
  }
  //    s1    e1
  // s2    e2
  if (dateUtils.isBefore(start2, start1) && dateUtils.isBefore(start1, end2)) {
    return true;
  }
  //    s1  e1
  // s2        e2
  if (dateUtils.isBefore(start2, start1) && dateUtils.isBefore(end1, end2)) {
    return true;
  }
  // s1        e1
  //    s2  e2
  if (dateUtils.isBefore(start1, start2) && dateUtils.isBefore(end2, end1)) {
    return true;
  }
  return false;
};
const generateSlotsForAvailability = (availability) => {
  let slotStart = new Date(availability.startDate);
  let slotEnd = dateUtils.iterateMinutes(slotStart, availability.meetingDuration);
  const availabilityEnd = new Date(availability.endDate);
  const slots = [];
  do {
    slotStart.setSeconds(1);
    slots.push({
      availabilityId: availability._id,
      start: slotStart,
      end: slotEnd,
    });
    slotStart = dateUtils.iterateMinutes(slotEnd, availability.breakDuration || 0);
    slotEnd = dateUtils.iterateMinutes(slotStart, availability.meetingDuration);
  } while (dateUtils.isBeforeOrEqual(slotEnd, availabilityEnd));
  return slots;
};

const takvimAvailableTimePickerCss = "takvim-available-time-picker.mobile date-picker-container dvn-date-picker{margin-right:0 !important}takvim-available-time-picker.desktop dvn-date-picker{margin-right:1rem !important}";

const meetingLocationTypes = [
  {
    name: 'Custom',
    value: 'custom',
  },
  {
    name: 'Jitsi Meet',
    value: 'jitsi',
  },
  {
    name: 'Zoom',
    value: 'zoom',
  },
];
const formErrors = (error) => {
  if (!error)
    return [];
  // TODO show proper error messages from apiSozluk
  return [
    string.capitalize(`${error.data.message.split('-').join(' ')}.`, false),
  ];
};
const formFields = (meetingTypes = [], meetingsByMeetingTypes = {}, isCustom, authPlatforms) => {
  let maxFieldCount = isCustom ? 2 : 0;
  const fields = [];
  const availableMeetingTypes = meetingTypes
    .filter(meetingType => { var _a; return (((_a = meetingsByMeetingTypes[meetingType.id]) === null || _a === void 0 ? void 0 : _a.length) || 0) < meetingType.maxCount; });
  if (meetingTypes && meetingTypes.length > 0) {
    maxFieldCount += 1;
    fields.push(new index$2.SingleChoiceField('meetingType', 'Select a Session', availableMeetingTypes.map(meetingType => new index$2.SingleChoiceFieldOption(meetingType.name, meetingType.id)), '', 'select').setErrorTitle('Session').require());
  }
  fields.push(...[
    new index$2.SingleChoiceField('locationType', 'Location Type', meetingLocationTypes
      // filter out the location types if user doesn't have the corresponding auth platform (zoom)
      .filter(locationType => {
      if (locationType.value === 'custom' || locationType.value === 'jitsi') {
        return true;
      }
      return !!authPlatforms.some(authPlatform => authPlatform.id === locationType.value);
    })
      .map(locationType => new index$2.SingleChoiceFieldOption(locationType.name, locationType.value)), '', 'select').setValue('jitsi')
      .setVisibility(isCustom)
      .require(),
    new index$3.TextField('location', 'Location', 'Meeting location')
      .addInterceptor('onFormChange', new ConcealerConditional(new Equal('locationType', 'custom')))
      .require()
      .hide()
  ]);
  return { fields, maxFieldCount };
};
let TakvimAvailableTimePicker = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.createMeeting = index.createEvent(this, "createMeeting", 7);
    this.meetingsByMeetingTypes = {};
    /**
     * Raw availabilities fetched from the api.
     */
    this.availabilities = [];
    /**
     * Availabilities that are generated by the raw availabilities considering their recurrence.
     * MAX_MONTH_FOR_RECURRENCE is used to limit the availabilities for the future.
     */
    this.generatedAvailabilities = [];
    this.meetingLocationType = 'jitsi';
    this.meetingLocation = '';
    this.isProgressing = true;
    this.weekStartDay = 'monday';
    this.onSizeChange = (size) => {
      this.size = size;
      this.selectedTime = undefined;
      if (this.isMobileUI()) {
        // reset the date otherwise the slot list dialog will pop when switched to mobile
        this.selectedDate = undefined;
      }
      else {
        // set the date otherwise the slot list will keep showing progress
        this.selectedDate = new Date();
      }
    };
    this.isMobileUI = () => this.size < ui.ResponsiveSize.Small;
    this.onSelectTime = async (e) => {
      this.selectedTime = e.detail;
      const showMeetingDetailsForm = !!this.selectedDate && !!this.selectedTime;
      if (showMeetingDetailsForm && !this.meetings && this.meetingTypes) {
        // get the meetings of the users to filter out the meeting types based on the number of meetings they have
        const { viewedUserId, calendarConfigId, userId } = this;
        this.isProgressing = true;
        const meetings = await this.apiTakvim.getMeetingsOfUser(calendarConfigId, [userId, viewedUserId]).catch(e => {
          this.error = e;
        }).finally(() => this.isProgressing = false);
        if (!meetings)
          return;
        this.meetings = meetings.results;
        const meetingsByMeetingTypes = {};
        this.meetings.forEach(meeting => {
          if (meetingsByMeetingTypes[meeting.meetingType]) {
            meetingsByMeetingTypes[meeting.meetingType].push(meeting);
          }
          else {
            meetingsByMeetingTypes[meeting.meetingType] = [meeting];
          }
        });
        this.meetingsByMeetingTypes = meetingsByMeetingTypes;
      }
    };
    this.onSubmitForm = async (event) => {
      const data = event.detail.values;
      const { location, locationType, meetingType } = data;
      const { startHour, endHour, availabilityId } = this.selectedTime;
      const meeting = {
        locations: [{
            address: location,
            type: locationType,
          }],
        meetingType,
        startDate: startHour.toISOString(),
        endDate: endHour.toISOString(),
        guests: [
          User.User.generateRef(this.viewedUserId),
          User.User.generateRef(this.userId),
        ],
        createdBy: User.User.generateRef(this.userId),
        status: 'active',
        calendar: { _ref: 'takvim-calendar-configs', _id: this.calendarConfigId },
      };
      if (availabilityId) {
        meeting.availability = {
          _ref: 'takvim-availabilities',
          _id: availabilityId
        };
      }
      this.createMeetingError = undefined;
      this.isProgressing = true;
      const createMeetingResponse = await this.apiTakvim.createMeeting(meeting).catch(e => {
        this.createMeetingError = e;
      }).finally(() => this.isProgressing = false);
      if (!createMeetingResponse)
        return;
      this.meetings = undefined;
      this.selectedTime = undefined;
      this.selectedDate = new Date(this.selectedDate.toISOString());
      this.createMeeting.emit(Object.assign(Object.assign({}, createMeetingResponse), meeting));
    };
  }
  async componentWillLoad() {
    this.uiHelper = new ui.ResponsiveUIHelper(this.el, this.onSizeChange);
    this.size = ui.ResponsiveUIHelper.getSize(this.el.parentElement.clientWidth);
  }
  async componentDidLoad() {
    const { viewedUserId, calendarConfigId } = this;
    const calenderConfig = await this.apiTakvim.getCalendarConfig(calendarConfigId).catch(e => {
      this.error = e;
    });
    if (!calenderConfig)
      return;
    this.calendarConfig = calenderConfig;
    const availabilities = await this.apiTakvim.getAvailabilitiesOfUser(calendarConfigId, viewedUserId).catch(e => {
      this.error = e;
    }).finally(() => this.isProgressing = false);
    if (!availabilities)
      return;
    this.availabilities = availabilities.results;
    this.generatedAvailabilities = generateAvailabilities(availabilities.results);
    if (!this.isMobileUI()) {
      // invoke onSelectDate for generating slots for today
      this.selectedDate = new Date();
    }
  }
  render() {
    const { calendarConfigId, calendarConfig, createMeetingError, generatedAvailabilities, isProgressing, meetingsByMeetingTypes, meetingTypes, selectedDate, selectedTime, strings, userId, membershipConfigId, viewedUserId, viewedUserMembershipConfigId, weekStartDay, } = this;
    const showMeetingDetailsForm = !!selectedDate && !!selectedTime;
    const { fields: meetingDetailsFormFields, maxFieldCount } = formFields(meetingTypes, meetingsByMeetingTypes, !(selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.availabilityId), this.userSettings.authPlatforms);
    const minFormHeight = `${Math.max(maxFieldCount * 100, (meetingTypes === null || meetingTypes === void 0 ? void 0 : meetingTypes.length) > 0 ? 200 : 120)}px`;
    const timeZone = this.userSettings.timeZone;
    const dialogTitle = `${index$1.momentTimezone(selectedDate).tz(timeZone).format('DD MMMM')}, ${index$1.momentTimezone(selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.startHour).tz(timeZone).format('HH:mm')} - ${index$1.momentTimezone(selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.endHour).tz(timeZone).format('HH:mm')}`;
    if (this.isMobileUI()) {
      return (index.h(index.Host, { class: "d-flex mobile" }, index.h("dvn-card", { class: "date-picker-container", bodyLeaned: true, leaned: true, elevation: 0, width: "100%" }, index.h("div", { class: "d-flex justify-content-center" }, index.h("dvn-date-picker", { embedded: true, leaned: true, value: generatedAvailabilities.map(ca => new Date(ca.startDate)), onChange: (e) => this.selectedDate = e.detail, strings: strings, weekStartDay: weekStartDay }))), index.h("dvn-dialog", { class: "confirmation-dialog", shown: !!selectedDate || showMeetingDetailsForm, onDismiss: (e) => {
          e.preventDefault();
          e.stopPropagation();
          this.createMeetingError = undefined;
          if (selectedTime) {
            this.selectedTime = undefined;
          }
          else {
            this.selectedDate = undefined;
          }
        }, raw: !!selectedDate && !showMeetingDetailsForm, title: dialogTitle }, (selectedDate && !showMeetingDetailsForm) &&
        index.h("takvim-available-time-picker-selected-day", { availabilities: this.generatedAvailabilities, calenderConfig: calendarConfig, selectedDate: selectedDate, userId: userId, membershipConfigId: membershipConfigId, userSettings: this.userSettings, viewedUserId: viewedUserId, viewedUserMembershipConfigId: viewedUserMembershipConfigId, calendarConfigId: calendarConfigId, apiTakvim: this.apiTakvim, onSelectTime: this.onSelectTime, strings: strings }), showMeetingDetailsForm &&
        index.h("div", { class: "ml-3 mr-3 mt-3 mb-2" }, index.h("div", null, strings.scheduleMeetingConfirmation, index.h("br", null), index.h("br", null)), index.h("doldurma-form", { key: `${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.startHour}-${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.endHour}`, fields: meetingDetailsFormFields, onSubmit: this.onSubmitForm, submitButtonLabel: strings.scheduleMeeting, progressing: isProgressing, formErrors: formErrors(createMeetingError), minHeight: minFormHeight, width: '100%' })))));
    }
    return (index.h(index.Host, { class: "d-flex desktop" }, index.h("dvn-date-picker", { embedded: true, leaned: true, value: generatedAvailabilities.map(ca => new Date(ca.startDate)), highlightedDay: this.selectedDate, onChange: (e) => this.selectedDate = e.detail, strings: strings, weekStartDay: weekStartDay }), index.h("takvim-available-time-picker-selected-day", { availabilities: this.generatedAvailabilities, calenderConfig: calendarConfig, selectedDate: selectedDate, userId: userId, membershipConfigId: membershipConfigId, userSettings: this.userSettings, viewedUserId: viewedUserId, viewedUserMembershipConfigId: viewedUserMembershipConfigId, calendarConfigId: calendarConfigId, apiTakvim: this.apiTakvim, onSelectTime: this.onSelectTime, strings: strings }), index.h("dvn-dialog", { class: "confirmation-dialog", shown: showMeetingDetailsForm, onDismiss: () => {
        this.selectedTime = undefined;
        this.createMeetingError = undefined;
      }, minHeight: '240px', title: dialogTitle }, index.h("div", null, strings.scheduleMeetingConfirmation, index.h("br", null), index.h("br", null)), index.h("doldurma-form", { key: `${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.startHour}-${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.endHour}`, fields: meetingDetailsFormFields, onSubmit: this.onSubmitForm, submitButtonLabel: strings.scheduleMeeting, progressing: isProgressing, formErrors: formErrors(createMeetingError), minHeight: minFormHeight, width: '100%' }))));
  }
  get el() { return index.getElement(this); }
};
TakvimAvailableTimePicker.style = takvimAvailableTimePickerCss;

const takvimAvailableTimePickerSelectedDayCss = "takvim-available-time-picker-selected-day{-ms-flex:1;flex:1;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}takvim-available-time-picker-selected-day .selected-day-container{-ms-flex:1;flex:1;max-height:calc(var(--date-picker-body-height) + 75px)}@-webkit-keyframes fadeInOpacity{0%{opacity:0;margin-left:10px}100%{opacity:1;margin-left:0}}@keyframes fadeInOpacity{0%{opacity:0;margin-left:10px}100%{opacity:1;margin-left:0}}takvim-available-time-picker-selected-day .selected-day-container .day-title{-webkit-animation-name:fadeInOpacity;animation-name:fadeInOpacity;-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out;-webkit-animation-duration:0.3s;animation-duration:0.3s}takvim-available-time-picker-selected-day .selected-day-container .progress-container{display:-ms-flexbox;display:flex;height:100%;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;padding-bottom:1rem}takvim-available-time-picker-selected-day .selected-day-container .selected-day-availabilities dvn-card{margin:0 0 0.5rem 0;text-align:center;font-size:0.9em}takvim-available-time-picker-selected-day .selected-day-container .no-availability-message{font-size:0.9em}takvim-available-time-picker-selected-day .selected-day-container .custom-time-picker{height:100%;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}takvim-available-time-picker-selected-day .selected-day-container .custom-time-picker table{-ms-flex:1;flex:1}takvim-available-time-picker-selected-day .selected-day-container .slots-container{height:100%;overflow:auto}";

const conflictSourceNames = {
  'google-calendar': 'Google Calendar',
  'microsoft-calendar': 'Microsoft Calendar',
};
let TakvimAvailableTimePickerSelectedDay = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.selectTime = index.createEvent(this, "selectTime", 7);
    /**
     * Availabilities filtered by the selected date.
     */
    this.availabilitiesForTheSelectedDate = [];
    /**
     * Duration options of the selected date. Used when there are multiple
     * availabilities for the same date with different durations.
     */
    this.durationForTheSelectedDate = [];
    /**
     * Time slots that are generated when duration (if needed)
     * and availabilities are selected.
     */
    this.timeSlots = [];
    /**
     * Custom time values.
     */
    this.isPickingCustomTime = false;
    this.customTime = { hour: 9, minute: 0 };
    this.customDuration = 30;
    /**
     * API related values.
     */
    this.isProgressing = false;
    this.availabilities = [];
    this.strings = i18n.takvimAvailableTimePickerSelectedDayI18nDefault;
    this.durations = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 75, 90, 105, 120];
    this.onSelectSlot = (slot) => {
      this.selectTime.emit({
        availabilityId: slot.availabilityId,
        startHour: slot.start,
        endHour: slot.end,
      });
    };
    this.onSelectCustomTime = () => {
      const timeZone = this.userSettings.timeZone;
      const date = this.selectedDate;
      const time = this.customTime;
      const timeString = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()} ${time.hour}:${time.minute}`;
      const startHour = index$1.momentTimezone.tz(timeString, 'D/M/YYYY h:mm', timeZone).toDate();
      const endHour = dateUtils.iterateMinutes(startHour, this.customDuration);
      this.selectTime.emit({ startHour, endHour });
    };
    this.onSelectDuration = async (duration) => {
      const { userId, viewedUserId, calendarConfigId } = this;
      this.selectedDurationAvailabilities = this.availabilitiesForTheSelectedDate.filter(a => a.meetingDuration === duration);
      // get the earliest start time and latest end time of the availabilities to fetch the unavailabilities for that time period
      const { startDate, endDate } = getTimeFrameOfAvailabilities(this.selectedDurationAvailabilities);
      this.isProgressing = true;
      const unavailabilitiesOfCurrentUser = await this.apiTakvim.getUnavailabilitiesOfUser(calendarConfigId, userId, startDate.toISOString(), endDate.toISOString()).catch(e => {
        this.error = e;
      });
      if (!unavailabilitiesOfCurrentUser)
        return;
      const unavailabilitiesOfOtherUser = await this.apiTakvim.getUnavailabilitiesOfUser(calendarConfigId, viewedUserId, startDate.toISOString(), endDate.toISOString()).catch(e => {
        this.error = e;
      }).finally(() => this.isProgressing = false);
      if (!unavailabilitiesOfOtherUser)
        return;
      this.timeSlots = generateSlotsForAvailabilities(this.selectedDurationAvailabilities, unavailabilitiesOfCurrentUser.results, unavailabilitiesOfOtherUser.results);
    };
  }
  componentWillLoad() {
    this.onSelectedDateChange(this.selectedDate);
  }
  onSelectedDateChange(selectedDate) {
    this.selectedDurationAvailabilities = undefined;
    this.timeSlots = [];
    this.isPickingCustomTime = false;
    if (!selectedDate) {
      return;
    }
    this.availabilitiesForTheSelectedDate = this.availabilities
      // filter based on the selected date
      .filter(ca => dateUtils.isSameDay(new Date(ca.startDate), selectedDate))
      // sort to show slots in order if there are multiple availabilities with the same duration
      .sort((a, b) => (dateUtils.isBeforeOrEqual(new Date(a.startDate), new Date(b.startDate)) ? -1 : 1));
    if (this.availabilitiesForTheSelectedDate.length === 1) {
      // select the first availability automatically
      this.onSelectDuration(this.availabilitiesForTheSelectedDate[0].meetingDuration);
      return;
    }
    const durationForTheSelectedDate = [];
    this.availabilitiesForTheSelectedDate.forEach(availability => {
      if (!durationForTheSelectedDate.includes(availability.meetingDuration)) {
        durationForTheSelectedDate.push(availability.meetingDuration);
      }
    });
    this.durationForTheSelectedDate = durationForTheSelectedDate;
  }
  ;
  render() {
    const { availabilitiesForTheSelectedDate, calenderConfig, durationForTheSelectedDate, isPickingCustomTime, isProgressing, selectedDate, selectedDurationAvailabilities, membershipConfigId, userSettings, viewedUserMembershipConfigId, timeSlots, strings, } = this;
    const isPickingOneOfAvailabilitiesOfTheSelectedDate = selectedDate && !selectedDurationAvailabilities
      && availabilitiesForTheSelectedDate.length > 1;
    const isPickingTimeSlot = !!selectedDurationAvailabilities;
    // get calendar preferences of the viewed user
    const calendarPreferences = calenderConfig === null || calenderConfig === void 0 ? void 0 : calenderConfig.membershipPreferences.find(preference => preference.membershipConfig._id === viewedUserMembershipConfigId);
    // check if the user membership is allowed to get custom time
    const eligibleMembershipsForCustomTime = (calendarPreferences === null || calendarPreferences === void 0 ? void 0 : calendarPreferences.eligibleMembershipsForCustomTime) || [];
    const canPickCustomTime = eligibleMembershipsForCustomTime
      .some(membershipConfig => membershipConfig._id === membershipConfigId);
    const { timeZone } = userSettings;
    let zoneName = '';
    timeZones.zoneConfig.forEach(group => {
      group.zones.forEach(zone => {
        if (userSettings.timeZone === zone.value) {
          zoneName = zone.name;
        }
      });
    });
    const cardHeader = `${calendar.CalendarUtils.format(selectedDate, 'DD MMMM YYYY')}`;
    if (!selectedDate) {
      return (index.h(index.Host, null, index.h("dvn-card", { extraClass: "selected-day-container", elevation: 0, leaned: true }, index.h("dvn-card-header", { title: cardHeader, slot: "header", separated: false }), index.h("div", { class: "progress-container" }, index.h("dvn-progress", { indefinite: true, tint: "primary" })))));
    }
    return (index.h(index.Host, null, index.h("dvn-card", { extraClass: "selected-day-container", elevation: 0, leaned: true }, index.h("div", { slot: "header", class: "available-time-picker-date-header p-3 d-flex justify-content-between align-content-center" }, index.h("h4", { key: cardHeader, class: "mt-0 mb-0 day-title" }, cardHeader), index.h("span", { class: "text-neutral" }, index.h("i", { class: 'uil uil-clock' }), zoneName)), isProgressing &&
      index.h("div", { class: "progress-container" }, index.h("dvn-progress", { indefinite: true, tint: "primary" })), index.h("div", { class: "custom-time-picker", style: { display: isPickingCustomTime ? 'flex' : 'none' } }, index.h("table", null, index.h("tbody", null, index.h("tr", null, index.h("td", null, strings.time), index.h("td", null, index.h("dvn-time-picker", { hour: this.customTime.hour, minute: this.customTime.minute, optionsContainerMaxHeight: "132px", leaned: true, onChange: (e) => this.customTime = e.detail }))), index.h("tr", null, index.h("td", null, strings.duration), index.h("td", null, index.h("dvn-select", { width: "99px", hideCaret: true, hideCheck: true, hideScrollbar: true, value: `${this.customDuration}`, optionsContainerMaxHeight: "112px", leaned: true, onChange: (e) => this.customDuration = Number(e.detail), enableSearch: true }, this.durations.map(minute => (index.h("dvn-select-option", { value: `${minute}` }, `${minute} ${strings.min}`)))))))), index.h("div", { class: "d-flex justify-content-end mt-2" }, index.h("dvn-button", { tint: "primary", onClick: this.onSelectCustomTime }, strings.done), index.h("dvn-button", { tint: "neutral", onClick: () => this.isPickingCustomTime = false }, strings.cancel))), index.h("div", { class: "selected-day-availabilities", style: { display: isPickingCustomTime ? 'none' : 'block' } }, isPickingOneOfAvailabilitiesOfTheSelectedDate &&
      index.h("div", { class: "duration-options-container" }, durationForTheSelectedDate.map(duration => (index.h("dvn-card", { elevation: 0, outlined: true, selectable: true, onClick: () => this.onSelectDuration(duration) }, index$4.SozlukApi.build(strings.bookWithDuration, { duration }))))), isPickingTimeSlot &&
      index.h("div", { class: "slots-container" }, timeSlots.map(slot => (index.h("dvn-card", { key: `${slot.availabilityId}-${slot.start}`, extraClass: "time-slot", elevation: 0, outlined: true, selectable: true, onClick: () => this.onSelectSlot(slot), tint: slot.sessionUserConflict ? 'danger' : undefined }, index$1.momentTimezone(slot.start).tz(timeZone).format('HH:mm'), " - ", index$1.momentTimezone(slot.end).tz(timeZone).format('HH:mm'), slot.sessionUserConflict &&
        index.h("div", { class: "session-user-conflict-message mt-1" }, index.h("small", null, index$4.SozlukApi.build(strings.conflictsWithCalendar, {
          meetingName: slot.sessionUserConflict.name,
          calendarName: conflictSourceNames[slot.sessionUserConflict.source],
        }))))))), (!isPickingOneOfAvailabilitiesOfTheSelectedDate && !isProgressing) &&
      (canPickCustomTime
        ? index.h("dvn-card", { extraClass: "pick-custom-time-button", elevation: 0, outlined: true, selectable: true, onClick: () => this.isPickingCustomTime = true }, strings.pickCustomTime)
        : (timeSlots.length === 0 && index.h("div", { class: "no-availability-message text-centered mt-3" }, availabilitiesForTheSelectedDate.length
          ? strings.noAvailabilityLeftForDay
          : strings.noAvailabilityForDay)))))));
  }
  static get watchers() { return {
    "selectedDate": ["onSelectedDateChange"]
  }; }
};
TakvimAvailableTimePickerSelectedDay.style = takvimAvailableTimePickerSelectedDayCss;

exports.takvim_available_time_picker = TakvimAvailableTimePicker;
exports.takvim_available_time_picker_selected_day = TakvimAvailableTimePickerSelectedDay;
