<script setup>

import { ref } from 'vue';
import { Button, FormGroup, TextInput } from '@cloudron/pankow';
import AppsModel from '../../models/AppsModel.js';

const { app } = defineProps([ 'app' ]);

const appsModel = AppsModel.create();

const busy = ref(false);
const errorMessage = ref('');
const upstreamUri = ref(app.upstreamUri);

async function onSubmit() {
  busy.value = true;
  errorMessage.value = '';

  const [error] = await appsModel.configure(app.id, 'upstream_uri', { upstreamUri: upstreamUri.value.replace(/\/$/, '') });
  if (error) {
    errorMessage.value = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  busy.value = false;
}

</script>

<template>
  <div>
    <form @submit.prevent="onSubmit()" autocomplete="off">
      <fieldset :disabled="busy">
        <input type="submit" style="display: none" :disabled="!upstreamUri"/>

        <FormGroup>
          <label for="upstreamUriInput">Upstream URI</label>
          <TextInput id="upstreamUriInput" v-model="upstreamUri"/>
          <p class="text-danger" v-if="errorMessage">{{ errorMessage }}</p>
        </FormGroup>
      </fieldset>
    </form>

    <br/>
    <Button @click="onSubmit()" :loading="busy" :disabled="busy || app.error || app.taskId" v-tooltip="app.taskId ? (app.error ? 'App is in error state' : 'App is busy') : ''">{{ $t('main.dialog.save') }}</Button>
  </div>
</template>
