"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.convertToRRule = void 0;
var _rrule = require("@kbn/rrule");
var _constants = require("../constants");
var _get_nth_by_weekday = require("./get_nth_by_weekday");
var _get_presets = require("./get_presets");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const convertToRRule = (startDate, timezone, recurringForm) => {
  var _form$customFrequency;
  const presets = (0, _get_presets.getPresets)(startDate);
  const rRule = {
    dtstart: startDate.toISOString(),
    tzid: timezone
  };
  if (!recurringForm) return {
    ...rRule,
    // default to yearly and a count of 1
    // if the maintenance window is not recurring
    freq: _rrule.Frequency.YEARLY,
    count: 1
  };
  let form = recurringForm;
  if (recurringForm.frequency !== 'CUSTOM') {
    form = {
      ...recurringForm,
      ...presets[recurringForm.frequency]
    };
  }
  const frequency = (_form$customFrequency = form.customFrequency) !== null && _form$customFrequency !== void 0 ? _form$customFrequency : form.frequency;
  rRule.freq = frequency;
  rRule.interval = form.interval;
  if (form.until) {
    rRule.until = form.until;
  }
  if (form.count) {
    rRule.count = form.count;
  }
  if (form.byweekday) {
    const byweekday = form.byweekday;
    rRule.byweekday = Object.keys(byweekday).filter(k => byweekday[k] === true).map(n => _constants.ISO_WEEKDAYS_TO_RRULE[Number(n)]);
  }
  if (form.bymonth) {
    if (form.bymonth === 'day') {
      rRule.bymonthday = [startDate.date()];
    } else if (form.bymonth === 'weekday') {
      rRule.byweekday = [(0, _get_nth_by_weekday.getNthByWeekday)(startDate)];
    }
  }
  if (frequency === _rrule.Frequency.YEARLY) {
    // rRule expects 1 based indexing for months
    rRule.bymonth = [startDate.month() + 1];
    rRule.bymonthday = [startDate.date()];
  }
  return rRule;
};
exports.convertToRRule = convertToRRule;