<script setup>

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, Switch } from 'pankow';
import { taskNameFromInstallationState } from '../../utils.js';
import AppRepairDialog from '../AppRepairDialog.vue';
import AppsModel from '../../models/AppsModel.js';

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

const appsModel = AppsModel.create();
const busyRestart = ref(false);
const debugMode = ref(false);
const debugModeBusy = ref(false);

async function onDebugMode(newValue) {
  debugModeBusy.value = true;

  const data = newValue ? {
    readonlyRootfs: false,
    cmd: [ '/bin/bash', '-c', 'echo "Repair mode. Use the webterminal or cloudron exec to repair. Sleeping" && sleep infinity' ]
  } : null;

  const [error] = await appsModel.configure(props.app.id, 'debug_mode', { debugMode: data });
  if (error) {
    debugModeBusy.value = false;
    debugMode.value = !newValue;
    return console.error(error);
  }

  // let the task start
  setTimeout(() => { debugModeBusy.value = false; }, 2000);
}

const repairDialog = useTemplateRef('repairDialog');
async function onRepair() {
  repairDialog.value.open(props.app);
}

async function onRestart() {
  busyRestart.value = true;

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

  busyRestart.value = false;
}

onMounted(() => {
  debugMode.value = !!props.app.debugMode;
});

</script>

<template>
  <div>
    <AppRepairDialog ref="repairDialog" />

    <label>{{ $t('app.repair.recovery.title') }}</label>
    <p v-html="$t('app.repair.recovery.description', { docsLink: 'https://docs.cloudron.io/troubleshooting/#unresponsive-app' })"></p>

    <div style="display: flex; justify-content: space-between;">
    <Switch v-model="debugMode" @change="onDebugMode" :disabled="debugModeBusy || app.error || app.taskId" v-tooltip="app.taskId ? (app.error ? 'App is in error state' : 'App is busy') : ''" label="Recovery Mode"/>
      <Button @click="onRestart()" :disabled="busyRestart || app.taskId || app.error || app.installationState === 'pending_restart'" :loading="busyRestart || app.installationState === 'pending_restart'" v-tooltip="app.error ? 'App is in error state' : (app.taskId ? 'App is busy' : '')">{{ $t('app.repair.recovery.restartAction') }}</Button>
    </div>

    <hr/>

    <label>{{ $t('app.repair.taskError.title') }}</label>
    <p>{{ $t('app.repair.taskError.description') }}</p>
    <p v-if="app.error">An error occurred during the <b>{{ taskNameFromInstallationState(app.error.installationState) }}</b> operation: <span class="text-danger"><b>{{ app.error.reason + ': ' + app.error.message }}</b></span></p>
    <Button @click="onRepair()" :disabled="app.taskId || !app.error" v-tooltip="app.taskId ? $t('app.repair.appIsBusyTooltip') : ''">{{ $t('app.repair.taskError.retryAction', { task: app.error ? taskNameFromInstallationState(app.error.installationState) : '' }) }}</Button>
  </div>
</template>
