<template>
  <div>
    <h3>Admin Session</h3>
    <div v-for="request in requestCmds" :key="request.keyword">
      <button @click="sendRequest(request)">{{ request.label }}</button>
    </div>
    <div v-for="response in responses" :key="response.cnt">
      <pre>{{ response.data }}</pre>
    </div>
  </div>
</template>

<script lang="ts">

import { Component, Prop, Vue } from 'vue-property-decorator'
import * as io from 'socket.io-client';

@Component
export default class AdminCommands extends Vue {
  @Prop() public connection;
  @Prop() public session;
  idToken: string = ''

  requestCmds = [
    { keyword: 'login', label: 'getCurrentLogins' },
    // { keyword: 'conn',  label: 'getCurrentConnections' },
    // { keyword: 'sub',   label: 'getSubscriptions' },
    { keyword: 'req',   label: 'getRequests' },
    // { keyword: 'res',   label: 'getResponses' },
  ];
  
  socket = null
  responses = []
  url = 'http://localhost:3011'
  cnt = 0

  setResponse(data) {
    this.responses = []

    if(Array.isArray(data) == false || data.length == 0) {
      this.cnt++
      this.responses.push({
        cnt: this.cnt,
        data: 'no results'
      })
      return
    }

    for (let index = 0; index < data.length; index++) {
      this.cnt++
      this.responses.push({
        cnt: this.cnt,
        data: JSON.stringify(
          this.parseData(data[index]),
          null, 3
        )
      })
    }
  }
  
  parseData(data) {
    if( data?.token ) {
      return this.parseLogin(data)
    }
    return this.parseRequest(data)
  }

  parseLogin(data) {
    return {
      "token": data.token, 
      "lastActionOn": data.lastActionOn, 
      "connections": data.connections.map(c => ({ 
        "transport": c.client.transport, 
        "id": c.client.id, 
      }))
    }
  }
// x = [
//    { 
//      "id": "9z55r61", 
//      "token": "9z55r67016", 
//      "lastActionOn": "2021-07-17T13:25:04.406Z", 
//      "timeout": 10000, 
//      "connections": [ 
//        { 
//          "isDone": false, 
//          "client": { 
//            "transport": "socketio", 
//            "id": "O6vmYhBbpHiDmibmAAAE", 
//            "address": "::1", 
//            "url": "/socket.io/?EIO=3&transport=polling&t=Ngqf3qf"
//           }
//         }
//       ]
//    }
  parseRequest(data) {
    const result = {
      ucpId: data.Message.header.security.ucpId,
      receivedDate: data.ReceivedDateTime,
      messageID: data.Message.header.messageID,
      messageType: data.Message.header.messageType,
    }
    if( result.messageType == 'Command' ) {
      result['command'] = data.Message.header.command
      if(result['command']=='Start') {
        result['ucpId'] = null
      }
    } else {
      result['query'] = data.Message.header.query
    }
    return result
  }

  connect(){
    const socket = io.connect(this.url)
    let cnt = 0;
    socket.on('admin_response', (data) => {
      cnt++;
      this.setResponse(data?.data);
    })

    socket.on('connect', (ws) => {
      console.info('admin connected', ws, socket?.id)
    });

    socket.connect();
    this.socket = socket;
  }

  sendRequest(request) {
    const keyword = request.keyword
    const options = {}
    this.socket.emit('admin_request',{ request: keyword, options }, (data)=>{
      console.log({ got: data })
    })
  }

  loginDisabled(){
    if ( this.idToken == null ) return true
    if ( this.connection.socketId == null ) return true
    if ( this.session.ucpId != null ) return true
    return false
  }

  mounted(){
      this.connect()
  }

}
</script>

<style>
</style>
