<script setup>

import { ref, useTemplateRef, computed } from 'vue';
import { Radiobutton, Dialog, FormGroup, SingleSelect, MultiSelect } from '@cloudron/pankow';
import BackupSitesModel from '../models/BackupSitesModel.js';
import { cronDays, cronHours, parseSchedule } from '../utils.js';

const emit = defineEmits([ 'success' ]);

const backupSitesModel = BackupSitesModel.create();

const site = ref({});
const busy = ref(false);
const formError = ref('');
const dialog = useTemplateRef('dialog');
const scheduleType = ref('');
const days = ref([]);
const hours = ref([]);
const configureRetention = ref(''); // this is 'name' and not 'id' of backupRetentions because SingleSelect needs strings
const isConfigureValid = computed(() => {
  return scheduleType.value === 'never' || (days.value.length > 0 && hours.value.length > 0);
});

async function onSubmit() {
  if (!isConfigureValid.value) return;

  busy.value = true;

  let schedule;
  if (scheduleType.value === 'pattern') {
    let daysPattern;
    if (days.value.length === 7) daysPattern = '*';
    else daysPattern = days.value;

    let hoursPattern;
    if (hours.value.length === 24) hoursPattern = '*';
    else hoursPattern = hours.value;

    schedule = `00 00 ${hoursPattern} * * ${daysPattern}`;
  } else {
    schedule = 'never';
  }

  let [error] = await backupSitesModel.setSchedule(site.value.id, schedule);
  if (error) {
    busy.value = false;
    formError.value = error.body ? error.body.message : 'Internal error';
    return console.error(error);
  }

  const selectedRetention = BackupSitesModel.backupRetentions.find(function (x) { return x.name === configureRetention.value; });
  [error] = await backupSitesModel.setRetention(site.value.id, selectedRetention.id);
  if (error) {
    busy.value = false;
    formError.value = error.body ? error.body.message : 'Internal error';
    return console.error(error);
  }

  emit('success');
  dialog.value.close();

  busy.value = false;
}

defineExpose({
  async open(s) {
    site.value = s;
    busy.value = false;
    formError.value = false;
    days.value = [];
    hours.value = [];

    const currentRetentionString = JSON.stringify(site.value.retention);
    const selectedRetention = BackupSitesModel.backupRetentions.find(function (x) { return JSON.stringify(x.id) === currentRetentionString; });
    configureRetention.value = selectedRetention ? selectedRetention.name : BackupSitesModel.backupRetentions[0].name;

    if (site.value.schedule === 'never') {
      scheduleType.value = 'never';
    } else {
      scheduleType.value = 'pattern';
      const result = parseSchedule(site.value.schedule);
      days.value = result.days; // Array of cronDays.id
      hours.value = result.hours; // Array of cronHours.id
    }

    dialog.value.open();
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('backups.configureBackupSchedule.title')"
     reject-style="secondary"
    :reject-label="$t('main.dialog.cancel')"
    :reject-active="!busy"
    :confirm-label="$t('main.dialog.save')"
    :confirm-busy="busy"
    :confirm-active="isConfigureValid"
    @confirm="onSubmit()"
  >
    <p>{{ $t('backups.configureBackupSchedule.schedule.context', { name: site.name }) }}</p>

    <div class="error-label" v-show="formError">{{ formError }}</div>

    <form @submit.prevent="onSubmit()" autocomplete="off">
      <fieldset>
        <FormGroup>
          <label for="daysInput">{{ $t('backups.configureBackupSchedule.schedule.title') }}</label>
          <div description v-html="$t('backups.configureBackupSchedule.schedule.description')"></div>

          <Radiobutton v-model="scheduleType" value="never" :label="$t('backups.configureBackupSchedule.disable')"/>
          <Radiobutton v-model="scheduleType" value="pattern" :label="$t('backups.configureBackupSchedule.enable')"/>
          <div v-if="scheduleType === 'pattern'" style="display: flex; align-items: center; gap: 10px; margin: 10px">
            <div>{{ $t('backups.configureBackupSchedule.days') }}: <MultiSelect id="daysInput" v-model="days" :options="cronDays" option-key="id" option-label="name"></MultiSelect></div>
            <div>{{ $t('backups.configureBackupSchedule.hours') }}: <MultiSelect v-model="hours" :options="cronHours" option-key="id" option-label="name"></MultiSelect></div>
            <div class="text-small text-danger" v-show="scheduleType === 'pattern' && !(hours.length !== 0 && days.length !== 0)">{{ $t('settings.updateScheduleDialog.selectOne') }}</div>
          </div>
        </FormGroup>

        <FormGroup>
          <label for="retentionInput">{{ $t('backups.configureBackupSchedule.retentionPolicy') }}</label>
          <!-- we do not used id as key because SingleSelect can only handle strings -->
          <SingleSelect id="retentionInput" v-model="configureRetention" :options="BackupSitesModel.backupRetentions" option-key="name" option-label="name" />
        </FormGroup>
      </fieldset>
    </form>
  </Dialog>
</template>
