<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 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);
  }

  const packageData = {
    ...result, // { manifest, publishState, creationDate, ts }
    versionsUrl: `${url}@${version || 'latest'}`,
    iconUrl: result.manifest.iconUrl // compat with app store format
  };

  emit('success', packageData);

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

defineExpose({
  open() {
    versionsUrl.value = '';
    formError.value = {};
    dialog.value.open();
  }
});

</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>

        <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>
