<script setup>

import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;

import { ref, onMounted, useTemplateRef, inject } from 'vue';
import { Button, TableView, InputDialog } from 'pankow';
import Section from '../components/Section.vue';
import DockerRegistryDialog from '../components/DockerRegistryDialog.vue';
import DockerRegistriesModel from '../models/DockerRegistriesModel.js';

const dockerRegistriesModel = DockerRegistriesModel.create();

const registries = ref([]);

const columns = {
  serverAddress: {
    label: t('settings.privateDockerRegistry.server'),
    sort: true
  },
  username: {
    label: t('settings.privateDockerRegistry.username'),
    sort: true
  },
  actions: {}
};

const features = inject('features');
const subscriptionRequiredDialog = inject('subscriptionRequiredDialog');

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

function onEditOrAdd(registry = null) {
  if (registry || features.value.privateDockerRegistry) dialog.value.open(registry);
  else subscriptionRequiredDialog.value.open();
}

async function onRemove(registry) {
  const yes = await inputDialog.value.confirm({
    message: t('settings.privateDockerRegistry.deleteQuestion'),
    confirmStyle: 'danger',
    confirmLabel: t('main.dialog.delete'),
    rejectLabel: t('main.dialog.cancel')
  });

  if (!yes) return;

  const [error] = await dockerRegistriesModel.remove(registry.id);
  if (error) console.error(error);

  await refresh();
}
async function refresh() {
  const [error, result] = await dockerRegistriesModel.list();
  if (error) return console.error(error);

  registries.value = result;
}

onMounted(async () => {
  await refresh();
});

</script>

<template>
  <Section :title="$t('settings.privateDockerRegistry.title')" :title-badge="features.privateDockerRegistry ? 'Upgrade' : ''">
    <InputDialog ref="inputDialog" />
    <DockerRegistryDialog ref="dialog" @success="refresh()"/>

    <template #header-buttons>
      <!-- TODO translate -->
      <Button icon="fa-solid fa-plus" @click="onEditOrAdd()">Add</Button>
    </template>

    <p v-html="$t('settings.privateDockerRegistry.description', { customAppsLink: 'https://docs.cloudron.io/custom-apps/tutorial/' })"></p>

    <TableView :columns="columns" :model="registries">
      <template #actions="registry">
        <div class="table-actions">
          <Button small tool secondary @click="onEditOrAdd(registry)" icon="fa fa-pencil-alt" />
          <Button small tool danger @click="onRemove(registry)" icon="far fa-trash-alt" />
        </div>
      </template>
    </TableView>
  </Section>
</template>
