import {get, post, put, remove} from './apiHelpers.js'
import {convertList, convertObject} from '@helpers/adapter/adapter.js'

const config = {
  id: "id",
  created_at: "created_at",
  updated_at: "updated_at",
  deleted_at: "deleted_at",
  name: "name",
  port: "port",
  proxy_ip: "proxy_ip",
  internet_uri: "internet_uri",
  description: "description",
  is_online: "is_online",
  site_ip: "device_ip",
}

const configToServer = {
  id: "id",
  created_at: "created_at",
  updated_at: "updated_at",
  deleted_at: "deleted_at",
  name: "name",
  port: "port",
  proxy_ip: "proxy_ip",
  internet_uri: "internet_uri",
  description: "description",
  is_online: "is_online",
  device_ip: "site_ip",
}

class Services {

  /**
   *
   * @param {String} apiAddr - path to service
   */

  constructor(apiAddr) {
    this.apiAddr = apiAddr
    this.config = config
    this.configToServer = configToServer
  }

  /**
   *
   * @returns {Array<Object>} res.data - all services
   */

  async getServices() {
    const res = await get(`${this.apiAddr}/servers`)
    return convertList(res.data, {config: this.config})
  }

  /**
   *
   * @param {Object} payload - add new service
   * @returns {Object} newService - added new service
   */

  async createService(payload) {
    let newService = []
    const updatedPort = parseFloat(payload.port)
    const updatedService = {...convertObject(payload, {config: this.configToServer}), port: updatedPort}
    await post(`${this.apiAddr}/servers`, updatedService).then(res => {
      newService = convertObject(res.value, {config: this.config})
    }).catch(err => {
      console.log('err', err)
    })
    return newService
  }

  /**
   *
   * @param {Object} payload - edit params in selected service
   * @returns {Object} resService - updated service with edited params
   */

  async updateService(payload) {
    let resService = []
    const updatedPort = parseFloat(payload.port)
    const updatedService = {...convertObject(payload, {config: this.configToServer}), port: updatedPort}
    if (payload.id) {
      await put(`${this.apiAddr}/servers`, updatedService, payload.id).then(res => {
        resService = convertObject(res.value, {config: this.config})
      }).catch(err => {
        console.log('err', err)
      })
    }
    return resService
  }

  /**
   *
   * @param {Number} id - id selected service for remove
   * @returns {Number} deletedServiceId - id removed service
   */

  async deleteService(id) {
    let deletedServiceId = null
    await remove(`${this.apiAddr}/servers`, id).then((res) => {
      deletedServiceId = res.id
    }).catch(err => {
      console.log('err', err)
    })
    return deletedServiceId
  }
}

export default Services
