<script setup>

import { ref, useTemplateRef } from 'vue';
import { Dialog, TextInput, FormGroup } from '@cloudron/pankow';
import CommunityModel from '../models/CommunityModel.js';

const communityModel = CommunityModel.create();

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

const dialog = useTemplateRef('dialog');
const form = useTemplateRef('form');

const formError = ref({});
const versionsUrl = ref('');
const busy = ref(false);
const unstable = ref(false);

const isFormValid = ref(false);
function validateForm() {
  isFormValid.value = form.value ? form.value.checkValidity() : false;
}

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

  busy.value = true;
  formError.value = {};

  const [url, version] = versionsUrl.value.split('@'); // hidden feature that user can input with version
  const [error, result] = await communityModel.getApp(url, version || 'latest');
  if (error) {
    formError.value.generic = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  unstable.value = !!result.unstable;

  const packageData = {
    ...result, // { manifest, publishState, creationDate, ts, unstable, versionsUrl }
    versionsUrl: result.versionsUrl,
    iconUrl: result.manifest.iconUrl // compat with app store format
  };

  emit('success', packageData);

  dialog.value.close();
  busy.value = false;
}

defineExpose({
  open() {
    versionsUrl.value = '';
    formError.value = {};
    unstable.value = false;
    dialog.value.open();
    setTimeout(validateForm, 100); // update state of the confirm button
  }
});

</script>

<template>
  <Dialog ref="dialog"
    title="Install Community App"
    :confirm-label="$t('main.action.add')"
    :confirm-busy="busy"
    :confirm-active="!busy && isFormValid"
    reject-style="secondary"
    :reject-label="$t('main.dialog.cancel')"
    :reject-active="!busy"
    @confirm="onSubmit()"
  >
    <form @submit.prevent="onSubmit()" autocomplete="off" ref="form" @input="validateForm()">
      <fieldset :disabled="busy">
        <input type="submit" style="display: none;" />

        <div class="warning-label">{{ $t('communityapp.installwarning') }}</div>
        <div class="error-label" v-if="unstable">{{ $t('communityapp.unstablewarning') }}</div>

        <FormGroup>
          <label for="urlInput">CloudronVersions.json URL</label>
          <TextInput id="urlInput" v-model="versionsUrl" required placeholder="https://example.com/CloudronVersions.json"/>
          <div class="error-label" v-if="formError.generic">{{ formError.generic }}</div>
        </FormGroup>
      </fieldset>
    </form>
  </Dialog>
</template>
