import {get, post, put, remove} from './apiHelpers.js'
import {convertObject, convertList} from './adapter/adapter.js'
import { config} from '@store/modules/proxy/StaticData.js';

const servConfig = {
  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
   * @param {Object} config - oldKey: newKey
   */

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

  /**
   *
   * @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: servConfig}), 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: servConfig}), 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

/**
 * Testing class Services
*/

// eslint-disable-next-line no-unused-vars
const apiTest = async () => {

  const services = new Services(import.meta.env.VITE_API_ADDR, config)

  // Testing get services
  console.log('Uploaded services, method getServices - start')
  const uploadedServices = await services.getServices()
  console.log('Uploaded services, method getServices - result:', uploadedServices)

  // Testing create service
  console.log('Added new service, method createService - start')
  const newService = await services.createService({
    name: "Test site for testing createService",
    port: 7777,
    site_ip: "172.25.78.151",
    proxy_ip: "172.25.78.151",
    description: 'Testing createService method',
  })
  let updatedServices = [...uploadedServices, newService]
  console.log('Added new service, method createService - result:', newService)

  // Testing update service
  console.log('Updated services, method updateService - start')
  const serviceWithNewParams = {...newService, name: 'Test site for testing updateService', description: 'Testing updateService method', port: 9999}
  const updatedService = await services.updateService(serviceWithNewParams)
  updatedServices = [...updatedServices.filter(service => service.id !== newService.id), updatedService]
  console.log('Updated services, method updateService - result:', updatedService)

  // Testing delete service
  console.log('Deleted service, method deleteService - start')
  const deletedServiceId = await services.deleteService(newService.id)
  console.log('Deleted service, method deleteService, get id from deleted service - result:', deletedServiceId)

  // Testing get services after delete
  const withoutDeletedService = updatedServices.filter(service => service.id !== newService.id)
  const updatedServicesAfterDelete = await services.getServices()
  console.log('Services after all tests:', updatedServicesAfterDelete)

  // Equal results

  const reg = new RegExp (`${updatedServicesAfterDelete.length}`, 'g')
  const lengthCurrServices = withoutDeletedService.length.toString()

  console.log('reg', reg)

  const isEqual = reg.test(lengthCurrServices)

  console.log('isCountServicesEqual', isEqual)
}

// Запуск теста api - расскомментировать функцию apiTest
// apiTest()
// тест api end

/**
 * Testing class Services end
 */