<template>
  <div class="sm:w-3/4 md:w-1/3 w-full dark:text-white">
    <h1 class="font-hairline mb-6 text-center">Register Access Point</h1>
    <form
      class="border-yellow-300 p-8 border-t-8 bg-white mb-6 rounded-lg shadow-lg"
      @submit.prevent="registerAccessPoint"
    >
      <div class="mb-4">
        <label class="font-bold text-gray-800 block mb-2"
          >AccessPoint Name aruba-ap-<input
            type="text"
            class="text-black block appearance-none w-full bg-white border border-gray-300 hover:border-gray-700 px-2 py-2 rounded shadow"
            v-model.trim="apName"
            placeholder="c01"
          />
        </label>
      </div>
      <div class="flex items-center justify-between">
        <button
          class="bg-green-600 hover:bg-green-400 text-white font-bold py-2 px-4 rounded"
          type="submit"
        >
          Register!
        </button>
      </div>
    </form>
  </div>
  <VTaskState
    v-for="task in tasks"
    :ap-name="task.apName"
    :task-i-d="task.taskID"
  ></VTaskState>
</template>

<script lang="ts">
import { reactive, ref, toRefs } from "vue";
import {
  getAccessPointByID,
  registerAccessPoint as apiRegisterAccessPoint,
} from "../api";
import VTaskState from "../components/VTaskState.vue";

export default {
  name: "RegisterAccessPoint",
  components: { VTaskState },
  props: {
    apID: {
      type: Number,
      required: false,
    },
  },
  setup(props: { apID?: number }) {
    const { apID } = toRefs(props);
    const apName = ref("");
    const tasks = reactive<{ apName: string; taskID: string }[]>([]);
    const finishedTasks = reactive<{ apName: string; taskID: string }[]>([]);

    async function getAccessPointSettings(id: number) {
      try {
        await getAccessPointByID(id).then((a) => (apName.value = a.ap_name));
      } catch (e) {
        console.error(e);
      }
    }
    if (!isNaN(apID?.value)) {
      getAccessPointSettings(apID.value);
    }

    async function registerAccessPoint() {
      try {
        const r = await apiRegisterAccessPoint(apName.value);
        tasks.push({ apName: apName.value, taskID: r["task-id"] });
      } catch (e) {
        console.error(e);
      }
    }

    return { apName, registerAccessPoint, tasks, finishedTasks };
  },
};
</script>

<style scoped></style>
