<script setup>

import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, InputDialog } from '@cloudron/pankow';
import { prettyLongDate } from '@cloudron/pankow/utils';
import { APP_TYPES, RSTATES, ISTATES } from '../../constants.js';
import AppsModel from '../../models/AppsModel.js';

const appsModel = AppsModel.create();

const inputDialog = useTemplateRef('inputDialog');

const props = defineProps([ 'app' ]);

const latestBackup = ref(null);

async function onUninstall() {
  const yes = await inputDialog.value.confirm({
    title: t('app.uninstallDialog.title'),
    message: t('app.uninstallDialog.description', { app: (props.app.label || props.app.fqdn) }),
    confirmStyle: 'danger',
    confirmLabel: t('app.uninstallDialog.uninstallAction'),
    rejectLabel: t('main.dialog.cancel'),
    rejectStyle: 'secondary',
  });

  if (!yes) return;

  const [error] = await appsModel.uninstall(props.app.id);
  if (error) return console.error(error);

  window.location.href = '/#/apps';
}

async function onArchive() {
  if (!latestBackup.value) return;

  const yes = await inputDialog.value.confirm({
    title: t('app.archiveDialog.title'),
    message: t('app.archiveDialog.description', { app: (props.app.label || props.app.fqdn), date: prettyLongDate(latestBackup.value.creationTime) }),
    confirmStyle: 'danger',
    confirmLabel: t('app.archive.action'),
    rejectLabel: t('main.dialog.cancel')
  });

  if (!yes) return;

  const [error] = await appsModel.archive(props.app.id, latestBackup.value.id);
  if (error) return console.error(error);

  window.location.href = '/#/apps';
}

const TARGET_RUN_STATE = {
  START: Symbol('start'),
  STOP: Symbol('stop'),
};

function targetRunState() {
  // if we have an error, we want to retry the pending state, otherwise toggle the runstate
  if (props.app.error) {
    if (props.app.error.installationState === ISTATES.PENDING_START) return TARGET_RUN_STATE.START;
    else return TARGET_RUN_STATE.STOP;
  } else {
    if (props.app.runState === RSTATES.STOPPED) return TARGET_RUN_STATE.START;
    else return TARGET_RUN_STATE.STOP;
  }
}

const toggleRunStateBusy = ref(false);
async function onStartApp() {
  toggleRunStateBusy.value = true;

  const [error] = await appsModel.start(props.app.id);
  if (error) {
    toggleRunStateBusy.value = false;
    return console.error(error);
  }

  setTimeout(() => toggleRunStateBusy.value = false, 3000);
}

async function onStopApp() {
  toggleRunStateBusy.value = true;

  const [error] = await appsModel.stop(props.app.id);
  if (error) {
    toggleRunStateBusy.value = false;
    return console.error(error);
  }

  setTimeout(() => toggleRunStateBusy.value = false, 3000);
}

onMounted(async () => {
  let [error, result] = await appsModel.backups(props.app.id);
  if (error) return console.error(error);

  latestBackup.value = result[0] || null;

  if (latestBackup.value) {
    [error, result] = await appsModel.listBackupSites(props.app.id);
    if (error) return console.error(error);

    latestBackup.value.siteName = result.find((s) => s.id === latestBackup.value.siteId).name;
  }
});

</script>

<template>
  <div>
    <InputDialog ref="inputDialog" />

    <div v-if="app.type !== APP_TYPES.PROXIED && targetRunState() === TARGET_RUN_STATE.START">
      <label>{{ $t('app.start.title') }}</label>
      <div v-html="$t('app.start.description')"></div>
      <br/>
      <Button primary :loading="toggleRunStateBusy" :disabled="app.error || toggleRunStateBusy" @click="onStartApp()">{{ $t('app.start.action') }}</Button>
    </div>

    <div v-if="app.type !== APP_TYPES.PROXIED && targetRunState() === TARGET_RUN_STATE.STOP">
      <label>{{ $t('app.stop.title') }}</label>
      <div v-html="$t('app.stop.description')"></div>
      <br/>
      <Button primary :loading="toggleRunStateBusy" :disabled="app.error || toggleRunStateBusy" @click="onStopApp()">{{ $t('app.stop.action') }}</Button>
    </div>

    <hr style="margin-top: 20px"/>

    <div v-if="app.type !== APP_TYPES.PROXIED">
      <label>{{ $t('app.archive.title') }}</label>
      <div v-html="$t('app.archive.description')"></div>
      <p class="text-bold text-success" v-if="latestBackup" v-html="$t('app.archive.latestBackupInfo', { date: prettyLongDate(latestBackup.creationTime), siteName: latestBackup.siteName })"></p>
      <p class="text-warning" v-else v-html="$t('app.archive.noBackup')"></p>
      <Button :disabled="!latestBackup" @click="onArchive()">{{ $t('app.archive.action') }}</Button>
    </div>

    <hr style="margin-top: 20px"/>

    <div>
      <label>{{ $t('app.uninstall.uninstall.title') }}</label>
      <div>{{ $t('app.uninstall.uninstall.description') }}</div>
      <br/>
      <Button danger @click="onUninstall()">{{ $t('app.uninstall.uninstall.uninstallAction') }}</button>
    </div>
  </div>
</template>
