<template>
  <div class="px-3 py-6">
    <PrimeFloatLabel variant="on">
      <PrimeSelect
        v-model="inputDeviceId"
        :options="audioInputsHack"
        option-label="label"
        option-value="deviceId"
        fluid
        input-id="inputDevice"
      />
      <label for="inputDevice">Input device</label>
    </PrimeFloatLabel>

    <div class="flex items-center gap-2 mt-3">
      <PrimeToggleSwitch v-model="autoGainControl" input-id="autoGainControl" />
      <label for="autoGainControl">Auto Gain Control</label>
    </div>

    <div class="flex items-center gap-2 mt-3">
      <PrimeToggleSwitch v-model="echoCancellation" input-id="echoCancellation" />
      <label for="echoCancellation">Echo Cancellation</label>
    </div>

    <div class="flex items-center gap-2 mt-3">
      <PrimeToggleSwitch v-model="noiseSuppression" input-id="noiseSuppression" />
      <label for="noiseSuppression">Noise Suppression</label>
    </div>

    <PrimeFloatLabel variant="on">
      <PrimeSelect
        v-model="outputDeviceId"
        :options="audioOutputsHack"
        option-label="label"
        option-value="deviceId"
        fluid
        class="mt-6"
        input-id="outputDevice"
      />
      <label for="outputDevice">Output device</label>
    </PrimeFloatLabel>

    <PrimeDivider />

    <PrimeButton
      v-if="isTauri"
      size="small"
      label="Check for Updates"
      fluid
      severity="info"
      :loading="checking"
      @click="onCheckForUpdates"
    />
  </div>

  <PrimeToast position="bottom-center" group="updater">
    <template #container="slotProps">
      <div class="p-3">
        <div class="font-medium text-lg mb-4">
          {{ slotProps.message.detail }}
        </div>
        <div class="flex gap-3">
          <PrimeButton size="small" label="Update now" @click="() => {}" />
          <PrimeButton size="small" label="Later" severity="secondary" outlined @click="slotProps.closeCallback()" />
        </div>
      </div>
    </template>
  </PrimeToast>
</template>

<script setup lang="ts">
definePageMeta({
  name: 'Preferences',
})
const { isTauri } = useApp()
const { checking, checkForUpdates } = useUpdater()
const {
  inputDeviceId,
  outputDeviceId,
  autoGainControl,
  noiseSuppression,
  echoCancellation,
  audioInputs,
  audioOutputs,
} = usePreferences()

const toast = useToast()

const audioInputsHack = computed(() => {
  return JSON.parse(JSON.stringify(audioInputs.value))
})
const audioOutputsHack = computed(() => {
  return JSON.parse(JSON.stringify(audioOutputs.value))
})

async function onCheckForUpdates() {
  const update = await checkForUpdates()

  toast.removeGroup('updater')

  if (!update) {
    toast.add({ severity: 'success', summary: 'You are up to date', closable: false, life: 1000 })

    return
  }

  toast.add({
    group: 'updater',
    severity: 'info',
    detail: `Version ${update?.version ?? '1.0.1'} is available!`,
    closable: false,
  })
}
</script>
