<!DOCTYPE html>
<html>
<head>
  <title>My first Vue app</title>
  <script src="https://unpkg.com/vue"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/js-cookie@beta/dist/js.cookie.min.js"></script>
</head>
<body>

  <h1>Chat</h1>

  <div id="app">
    <div>{{ message }}</div>
    <div>
      <input v-model="message">
    </div>
    <div>
      <button @click="post">Post</button>
      <button @click="send">Send</button>
    </div>
    <div>
      <button @click="login">Login</button>
      <button @click="logout">Logout</button>
    </div>
    <div v-for="m in messages">{{ m }}</div>
  </div>

  <script>
    var app = new Vue({
      el: '#app',
      data: {
        messages: [],
        message: 'Hello Vue!',
        socket: null
      },
      mounted() {
        axios.defaults.xsrfCookieName = 'csrftoken';
        axios.defaults.xsrfHeaderName = 'X-CSRFToken';

        this.socket = new WebSocket('ws://' + window.location.host + '/ws/signals');

        this.socket.onmessage = (e) => {
            var data = JSON.parse(e.data);
            this.messages.push(data.data);
            console.log(this.messages);
        };

        this.socket.onclose = (e) => {
            console.log('Chat socket closed unexpectedly');
        };
      },
      methods: {
        async login() {
          const response = await axios.post('/login')
          console.log(response.data)
        },
        async logout() {
          const response = await axios.post('/logout')
          console.log(response.data)
        },
        async post() {
          console.log(Cookies.get('csrftoken'));
          const response = await axios.put('/message', {'message': this.message})
          console.log(response.data)
        },
        send() {
          console.log(this.message);
          this.socket.send(JSON.stringify({
              'message': this.message
          }));
        }
      }
    })
  </script>
</body>
</html>
