<script lang="ts" setup>
import { WAN_ACCESS_TYPE, WAN_FORWARD_TYPE } from '~/composables/gql/graphql';
import { useUnraidApiSettingsStore } from '~/store/unraidApiSettings';

const apiSettingsStore = useUnraidApiSettingsStore();

const accessType = ref<WAN_ACCESS_TYPE>(WAN_ACCESS_TYPE.Disabled);
const forwardType = ref<WAN_FORWARD_TYPE | null>(null);
const port = ref<number | null>(null);

onMounted(async () => {
  const remoteAccessSettings = await apiSettingsStore.getRemoteAccess();
  accessType.value =
    remoteAccessSettings?.accessType ?? WAN_ACCESS_TYPE.Disabled;
  forwardType.value = remoteAccessSettings?.forwardType ?? null;
  port.value = remoteAccessSettings?.port ?? null;
});

const setRemoteAccess = () => {
  apiSettingsStore.setupRemoteAccess({
    accessType: accessType.value,
    ...(forwardType.value ? { forwardType: forwardType.value } : {}),
    ...(port.value ? { port: port.value } : {}),
  });
};

watch(accessType, (newVal) => {
  if (newVal !== WAN_ACCESS_TYPE.Disabled) {
    forwardType.value = WAN_FORWARD_TYPE.Static;
  }
});
</script>

<template>
  <div class="flex flex-col">
    <h2>Setup Remote Access</h2>
    <label for="forwardType">Forward Type</label>
    <select id="forwardType" v-model="accessType">
      <option v-for="(val, index) in Object.values(WAN_ACCESS_TYPE)" :key="index" :value="val">
        {{ val }}
      </option>
    </select>
    <template v-if="accessType !== WAN_ACCESS_TYPE.Disabled">
      <label for="forwardType">Forward Type</label>
      <select id="forwardType" v-model="forwardType">
        <option v-for="(val, index) in Object.values(WAN_FORWARD_TYPE)" :key="index" :value="val">
          {{ val }}
        </option>
      </select>
    </template>
    <template v-if="forwardType === WAN_FORWARD_TYPE.Static && accessType !== WAN_ACCESS_TYPE.Disabled">
      <label for="port">Port</label>
      <input id="port" v-model="port" type="number">
    </template>

    <button @click="setRemoteAccess">
      Save
    </button>
  </div>
</template>
