let isConnected = false

const webSocketServer =  "dev.sedibelo.com"

const socketPort = 4433
const protocol = "wss"
const smtServer = `${protocol}://${webSocketServer}:${socketPort}`
let client = null
let num = 0
const excempt = ['LOGIN', 'SIGNIN']
const util = {
  transformTime(dt) {
    const hour = ('0' + dt.getHours()).substr(-2)
    const minutes = ('0' + dt.getMinutes()).substr(-2)
    return `${hour}:${minutes}`
  },
  transformDate(date) {
    return date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).substr(-2) + '-' + ('0' + (date.getDate())).substr(-2)
    // return date.toISOString().split('T')[0]
  },
  async sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  },
  async connectoToServer() {
    client = new WebSocket(smtServer);

    return new Promise(resolve => {
      client.onopen = async function (event) {
        //if (DEBUG) console.log("App Data Connection Established");
        // getTaxiRanks();
        let num = 0
        while (client.readyState !== 1 && num < 10) {
          await new Promise(resolve => setTimeout(resolve, 500))
          //console.log(client.readyState)
          isConnected = false
        }
        if (num < 10) {
          isConnected = true
          //console.log(client)
          resolve(true)
        }
        else {
          resolve(false)
        }

      }
    })
  },
  async sendData(jsonData) {
    
    await this.sleep(200)
    //console.log({ jsonData })
    if (isConnected === false || client.readyState !== 1) {
      await this.connectoToServer()
    }
    client.send(JSON.stringify(jsonData))
    return new Promise(resolve => {
      client.addEventListener("message", function (event) {
        try {
          const result = JSON.parse(event.data)
          // console.log(result)
          if (result.action === 'USERMESSAGE') {
            //console.log(result)
          }
          //console.log({ resultData: result, action: jsonData.action })
          resolve(result);
        } catch (e) {
          //console.log(e);
          resolve(event.data);
        }
      });
    })
  },
  async login(username, password) {
    const input = {
      action: 'LOGIN',
      username,
      password
    }
    return await this.sendData(input)
  },


}

window.util = util;