<script setup>

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

const usersModel = UsersModel.create();

const dialog = useTemplateRef('dialog');
const user = ref({});
const formError = ref('');
const password = ref('');
const success = ref(false);
const busy = ref(false);

// https://stackoverflow.com/questions/1497481/javascript-password-generator
function onGeneratePassword() {
  const length = 12;
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let tmp = '';

  for (var i = 0, n = charset.length; i < length; ++i) {
    tmp += charset.charAt(Math.floor(Math.random() * n));
  }

  password.value = tmp;
}

async function onSubmit() {
  busy.value = true;

  const [error] = await usersModel.setGhost(user.value.id, password.value);
  if (error) {
    busy.value = false;
    formError.value = error.body ? error.body.message : 'Internal error';
    return console.error(error);
  }

  busy.value = false;
  success.value = true;
}

defineExpose({
  async open(u) {
    u = JSON.parse(JSON.stringify(u)); // make a copy
    user.value = u;
    success.value = false;
    password.value = '';
    formError.value = '';

    dialog.value.open();
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('users.setGhostDialog.title')"
    :reject-label="success ? $t('main.dialog.close') : $t('main.dialog.cancel')"
     reject-style="secondary"
    :confirm-label="success ? '' : $t('users.setGhostDialog.setPassword')"
    :confirm-busy="busy"
    @confirm="onSubmit()"
  >
    <p>{{ $t('users.setGhostDialog.context', { username: user.username }) }}</p>
    <p>{{ $t('users.setGhostDialog.description') }}</p>
    <p class="text-danger" v-show="formError">{{ formError }}</p>
    <form @submit.prevent="onSubmit()" autocomplete="off">
      <fieldset :disabled="busy">
        <FormGroup>
          <label for="passwordInput">{{ $t('users.setGhostDialog.password') }}</label>
          <InputGroup>
            <TextInput id="passwordInput" v-model="password" style="flex-grow: 1;"/>
            <ClipboardButton v-if="success" :value="password" />
            <Button tool v-else @click="onGeneratePassword()" v-tooltip="$t('users.setGhostDialog.generatePassword')" icon="fa fa-key" />
          </InputGroup>
        </FormGroup>
      </fieldset>
    </form>
  </Dialog>
</template>
