<template>
  <form @submit.prevent="connect">
    <div v-show="apiMessage.type" class="callout" :class="{ success: apiMessage.type === 'success', alert: apiMessage.type === 'error' }">
      <p>{{ apiMessage.msg }}</p>
    </div>

    <div class="grid-x">
      <div class="cell">
        <label>
          Server <input type="text" v-model="modelValue.server" required>
        </label>
      </div>
    </div>
    <div class="grid-x">
      <div class="cell">
        <label>
          Port
          <Select
            v-model="modelValue.port"
            required
            :options="ports"
            :config="{ tags: true }"
          />
        </label>
      </div>
    </div>
    <label>
      Username <input type="text" v-model="modelValue.username">
    </label>
    <label>
      Passwort <input type="password" v-model="modelValue.password">
    </label>
    <div class="grid-x">
      <div class="cell">
        <input :id="`tls-${uid}`" type="checkbox" v-model="modelValue.tls">
        <label :for="`tls-${uid}`">TLS enabled</label>
      </div>
    </div>
    <button class="button" type="submit">
      Connect
    </button>
  </form>
</template>

<script setup>
import { inject, onMounted, ref } from 'vue';
import Select from '~/components/Select';

const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);

const $electron = inject('electron');

const uid = crypto.getRandomValues(new Uint8Array(1));
const apiMessage = ref({
  type: '',
  msg: '',
});

const ports = ref([...new Set([
  143,
  993,
  Number(props.modelValue.port),
])].map((port) => ({ id: port, text: port })));

function connect() {
  $electron.ipcRenderer.send('imap:connect', JSON.parse(JSON.stringify(props.modelValue)));
  emit('connect');
}

onMounted(() => {
  $electron.ipcRenderer.on('imap:connect:reply', (_event, _success) => {
    apiMessage.value = {
      type: 'success',
      msg: 'Connected!',
    };
  });

  $electron.ipcRenderer.on('imap:connect:error', (_event, error) => {
    apiMessage.value = {
      type: 'error',
      msg: error,
    };
  });
});
</script>

<style lang="scss">
</style>
