<script setup>
import { ref, onMounted } from 'vue'

const input = ref('')
const msgs = ref(['Server: Welcome to chat app', 'Server: This is an example message'])
let ws;

async function sendMsg(ev) {
  ev.preventDefault()

  let msg = input.value
  input.value = ''

  ws.send(msg)
}

onMounted(async () => {
  let proto = window.location.protocol == 'https:' ? 'wss://' : 'ws://'
  let host = window.location.host
  ws = new WebSocket(proto + host + "/api/ws")

  ws.onerror = function (event) {
    console.log('WebSocket connection failed:', event);
    //alert("Not logged in!")
    window.location.hash = "/login"
  };

  ws.onmessage = function (event) {
    console.log(event)
    msgs.value.push(event.data)
  };

  console.log(ws)
})
</script>

<template>
  <main>
    <div class="overflow-auto position-relative pb-5">
      <div v-for="msg in msgs" class="card m-3 text-bg-secondary">
        <div class="card-body">{{ msg }}</div>
      </div>
      <!--
      <div v-for="msg in msgs" class="input-group">
        <div class="alert alert-primary">User</div>
        <div class="alert alert-secondary">{{ msg }}</div>
      </div>
        -->
      <form onsubmit="event.preventDefault();" class="container-fluid fixed-bottom mb-3">
        <div class="input-group">
          <input v-model="input" type="text" class="form-control text-bg-secondary" placeholder="Type message here"
            aria-label="Chat message" aria-describedby="button-submit">
          <button @click="sendMsg" class="btn btn-primary" id="button-submit">Send</button>
        </div>
      </form>
    </div>
  </main>
</template>

