<!DOCTYPE html>
<html lang="en" data-bs-theme="auto">

<head>
  <%- header %>
</head>

<body id="app" v-cloak>
  <Navbar></Navbar>
  <div id="content" class="container">
    <h1 class="my-4 text-center">{{ $t('pin.pin_pairing') }}</h1>
    <form class="form d-flex flex-column align-items-center" id="form" @submit.prevent="registerDevice">
      <div class="card flex-column d-flex p-4 mb-4">
        <div class="input-group mt-2">
          <span class="input-group-text">
            <hash :size="18" class="icon"></hash>
          </span>
          <input type="text" pattern="\d*" :placeholder="`${$t('navbar.pin')}`" autofocus id="pin-input" class="form-control" required />
        </div>
        <div class="input-group my-4">
          <span class="input-group-text">
            <monitor :size="18" class="icon"></monitor>
          </span>
          <input type="text" :placeholder="`${$t('pin.device_name')}`" id="name-input" class="form-control" required />
        </div>
        <button class="btn btn-primary">
          <forward :size="18" class="icon"></forward>
          {{ $t('pin.send') }}
        </button>
      </div>
      <div class="alert alert-warning">
        <b>{{ $t('_common.warning') }}</b> {{ $t('pin.warning_msg') }}
      </div>
      <div id="status"></div>
    </form>
  </div>
</body>

<script type="module">
  import { createApp } from 'vue'
  import { initApp } from './init'
  import Navbar from './Navbar.vue'
  import { apiFetch } from './fetch_utils'
  import {
    Forward,
    Hash,
    Monitor,
  } from '@lucide/vue'

  let app = createApp({
    components: {
      Navbar,
      Forward,
      Hash,
      Monitor,
    },
    inject: ['i18n'],
    methods: {
      registerDevice(e) {
        let pin = document.querySelector("#pin-input").value;
        let name = document.querySelector("#name-input").value;
        document.querySelector("#status").innerHTML = "";
        let b = JSON.stringify({pin: pin, name: name});
        apiFetch("./api/pin", {
          method: "POST",
          headers: {
            'Content-Type': 'application/json'
          },
          body: b
        })
          .then((response) => response.json())
          .then((response) => {
            if (response.status === true) {
              document.querySelector(
                "#status"
              ).innerHTML = `<div class="alert alert-success" role="alert">${this.i18n.t('pin.pair_success')}</div>`;
              document.querySelector("#pin-input").value = "";
              document.querySelector("#name-input").value = "";
            } else {
              document.querySelector(
                "#status"
              ).innerHTML = `<div class="alert alert-danger" role="alert">${this.i18n.t('pin.pair_failure')}</div>`;
            }
          });
      }
    }
  });

  initApp(app);
</script>
