<script setup>

import { ref, onMounted, useTemplateRef, computed } from 'vue';
import { FormGroup, TextInput, Button, TagInput } from '@cloudron/pankow';
import ImagePicker from '../ImagePicker.vue';
import AppsModel from '../../models/AppsModel.js';
import { API_ORIGIN } from '../../constants.js';
import { getDataURLFromFile } from '../../utils.js';

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

const appsModel = AppsModel.create();

const imagePicker = useTemplateRef('imagePicker');
const busy = ref(false);
const labelError = ref('');
const tagsError = ref('');
const iconError = ref('');
const label = ref('');
const tags = ref([]);
const iconUrl = ref('');

let iconFile = 'src';
function onIconChanged(file) {
  iconFile = file;
}

const haveValuesChanged = computed(() => {
  return (label.value !== props.app.label) || (tags.value.join() !== props.app.tags.join()) || (iconFile !== 'src');
});

async function onSubmit() {
  busy.value = true;
  labelError.value = '';
  tagsError.value = '';
  iconError.value = '';

  if (iconFile !== 'src') {
    if (iconFile === 'fallback') { // user reset the icon
      const [error] = await appsModel.configure(props.app.id, 'icon', { icon: '' });
      if (error) {
        iconError.value = error.body ? error.body.message : 'Internal error';
        return error;
      }
    } else { // user loaded custom icon
        const tmp = (await getDataURLFromFile(iconFile)).replace(/^data:image\/[a-z]+;base64,/, '');
        const [error] = await appsModel.configure(props.app.id, 'icon', { icon: tmp });
        if (error) {
          iconError.value = error.body ? error.body.message : 'Internal error';
          return error;
        }
    }
    iconUrl.value = `${API_ORIGIN}/api/v1/apps/${props.app.id}/icon?ts=${Date.now()}`; // will also reset the ImagePicker
    iconFile = 'src';
  }

  if (label.value !== props.app.label) {
    const [error] = await appsModel.configure(props.app.id, 'label', { label: label.value });
    if (error) {
      labelError.value = error.body ? error.body.message : 'Internal error';
      busy.value = false;
      return console.error(error);
    }
  }

  if (tags.value.join() !== props.app.tags.join()) {
    const [error] = await appsModel.configure(props.app.id, 'tags', { tags: tags.value });
    if (error) {
      tagsError.value = error.body ? error.body.message : 'Internal error';
      busy.value = false;
      return console.error(error);
    }
  }

  busy.value = false;
}

onMounted(() => {
  label.value = props.app.label;
  tags.value = props.app.tags;
  // iconUrl is the appstore icon or user icon. there is no way to differentiate. when null (custom apps), neither is set.
  // the delete button in the icon can be used to unset user icon and use the appstore icon. unfortunately, it will also appear for the appstore icon
  iconUrl.value = props.app.iconUrl;
});

</script>

<template>
  <div>
    <div style="display: inline-block;">
      <label>{{ $t('app.display.icon') }}</label>
      <ImagePicker ref="imagePicker" mode="simple" :src="iconUrl" fallback-src="/img/appicon_fallback.png" @changed="onIconChanged" :size="512" display-height="96px"/>
    </div>

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

        <FormGroup>
          <label for="labelInput">{{ $t('app.display.label') }}</label>
          <TextInput id="labelInput" v-model="label"/>
          <div class="error-label" v-if="labelError">{{ labelError }}</div>
        </FormGroup>

        <FormGroup>
          <label for="tagsInput">{{ $t('app.display.tags') }}</label>
          <TagInput id="tagsInput" v-model="tags" v-tooltip="$t('app.display.tagsTooltip')"/>
          <small class="helper-text">{{ $t('app.display.tagsPlaceholder') }}</small>
          <div class="error-label" v-if="tagsError">{{ tagsError }}</div>
        </FormGroup>
      </fieldset>
    </form>
    <br/>
    <Button @click="onSubmit()" :loading="busy" :disabled="busy || !haveValuesChanged">{{ $t('app.display.saveAction') }}</Button>
  </div>
</template>
