<script setup>

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

import moment from 'moment-timezone';
import { ref, onMounted, useTemplateRef, computed } from 'vue';
import { Button, Dialog, SingleSelect, FormGroup, TextInput, TableView, InputDialog } from '@cloudron/pankow';
import { prettyLongDate, copyToClipboard } from '@cloudron/pankow/utils';
import Section from './Section.vue';
import AppPasswordsModel from '../models/AppPasswordsModel.js';
import AppsModel from '../models/AppsModel.js';

const appPasswordsModel = AppPasswordsModel.create();
const appsModel = AppsModel.create();

const newDialog = useTemplateRef('newDialog');
const inputDialog = useTemplateRef('inputDialog');
const passwords = ref([]);
const columns = {
  name: {
    label: t('profile.appPasswords.name'),
    sort: true
  },
  label: {
    label: t('profile.appPasswords.app'),
    sort: true,
    hideMobile: true,
  },
  creationTime: {
    label: t('main.table.date'),
    hideMobile: true,
    sort(a, b) {
      if (!a) return 1;
      if (!b) return -1;
      return moment(a).isBefore(b) ? 1 : -1;
    }
  },
  actions: {}
};

// new dialog props
const addedPassword = ref('');
const passwordName = ref('');
const identifiers = ref([]);
const identifier = ref('');

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

  // setup label for the table UI
  result.forEach(function (password) {
    if (password.identifier === 'mail') return password.label = password.identifier;
    const app = appsById[password.identifier];
    if (!app) return password.label = password.identifier + ' (App not found)';

    const ftp = app.manifest.addons && app.manifest.addons.localstorage && app.manifest.addons.localstorage.ftp;
    const labelSuffix = ftp ? ' - SFTP' : '';
    password.label = app.label ? app.label + ' (' + app.fqdn + ')' + labelSuffix : app.fqdn + labelSuffix;
  });

  passwords.value = result;
}

function onReset() {
  setTimeout(() => {
    passwordName.value = '';
    identifier.value = '';
    addedPassword.value = '';
  }, 500);
}

const isValid = computed(() => {
  if (!passwordName.value) return false;
  if (!identifier.value) return false;
  return true;
});

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

  addedPassword.value = '';

  const [error, result] = await appPasswordsModel.add(identifier.value, passwordName.value);
  if (error) return console.error(error);

  addedPassword.value = result.password;
  passwordName.value = '';
  identifier.value = '';

  await refresh();
}

function onCopyToClipboard(password) {
  copyToClipboard(password);
  window.pankow.notify({ type: 'success', text: 'Password copied!' });
}

async function onRemove(id, name) {
  const yes = await inputDialog.value.confirm({
    message: t('profile.removeAppPassword.title', { name }),
    confirmStyle: 'danger',
    confirmLabel: t('main.dialog.yes'),
    rejectLabel: t('main.dialog.no')
  });

  if (!yes) return;

  const [error] = await appPasswordsModel.remove(id);
  if (error) return console.error(error);

  await refresh();
}

onMounted(async () => {
  // build the password identifier selection model
  identifiers.value = [{ id: 'mail', label: 'Mail client' }];

  const [error, apps] = await appsModel.list();
  if (error) return console.error(error);

  apps.forEach(function (app) {
    if (!app.manifest.addons) return;
    if (app.manifest.addons.email) return;

    const ftp = app.manifest.addons.localstorage && app.manifest.addons.localstorage.ftp;
    const sso = app.sso && (app.manifest.addons.ldap || app.manifest.addons.proxyAuth);

    if (!ftp && !sso) return;

    let labelSuffix = '';
    if (ftp && sso) labelSuffix = ' - SFTP & App Login';
    else if (ftp) labelSuffix = ' - SFTP Only';

    const label = app.label ? app.label + ' (' + app.fqdn + ')' + labelSuffix : app.fqdn + labelSuffix;
    identifiers.value.push({ id: app.id, label: label });

    // stash for later use in table labels
    appsById[app.id] = app;
  });

  await refresh();
});

</script>

<template>
  <div>
    <InputDialog ref="inputDialog" />

    <Dialog ref="newDialog"
      :title="$t('profile.createAppPassword.title')"
      :confirm-label="addedPassword ? '' : $t('profile.createAppPassword.generatePassword')"
       confirm-style="primary"
      :reject-label="$t('main.dialog.close')"
       reject-style="secondary"
      @confirm="onSubmit()"
      @close="onReset()"
    >
      <div>
        <Transition name="slide-left" mode="out-in">
          <div v-if="!addedPassword">
            <form @submit.prevent="onSubmit()" autocomplete="off">
              <input style="display: none" type="submit" :disabled="!isValid"/>
              <FormGroup>
                <label for="passwordName">{{ $t('profile.createAppPassword.name') }}</label>
                <TextInput id="passwordName" v-model="passwordName" required/>
              </FormGroup>

              <FormGroup>
                <label>{{ $t('profile.createAppPassword.app') }}</label>
                <SingleSelect outline v-model="identifier" :options="identifiers" option-label="label" option-key="id" />
              </FormGroup>
            </form>
          </div>
          <div v-else>
            {{ $t('profile.createAppPassword.description') }}
            <TextInput v-model="addedPassword" readonly/>
            <Button tool @click="onCopyToClipboard(addedPassword)" icon="fa fa-clipboard" />
            <p>{{ $t('profile.createAppPassword.copyNow') }}</p>
          </div>
        </Transition>
      </div>
    </Dialog>

    <Section :title="$t('profile.appPasswords.title')">
      <template #header-buttons>
        <Button @click="newDialog.open()" icon="fa fa-plus">{{ $t('profile.appPasswords.newPassword') }}</Button>
      </template>

      <p>{{ $t('profile.appPasswords.description') }}</p>
      <br/>

      <TableView :columns="columns" :model="passwords" :placeholder="$t('profile.appPasswords.noPasswordsPlaceholder')">
        <template #creationTime="password">{{ prettyLongDate(password.creationTime) }}</template>
        <template #actions="password">
          <div class="table-actions">
            <Button small tool danger @click="onRemove(password.id, password.name)" v-tooltip="$t('profile.appPasswords.deletePasswordTooltip')" icon="far fa-trash-alt" />
          </div>
        </template>
      </TableView>
    </Section>
  </div>
</template>
