import { addedService, updatedService, removedNewService, deletedService } from "./helpers"
import { isEmpty } from "ramda"

class ServiceOfServices {
  constructor(adapterOfServices, store) {
    this.adapterOfServices = adapterOfServices
    this.store = store
  }

  async fetchServices() {
    const services = await this.adapterOfServices.getServices()
    this.store.dispatch('services/saveServices', services)
    return services
  }

  async addNewServiceLayout() {
    const newService = {"port": "", "name": "", id: -1}
    this.store.dispatch('services/addedNewServiceLayout', newService)
  }

  async createNewService(newService) {
    this.store.commit('services/setIsSaveData', false)
    this.store.commit('services/setSelectedService', null)
    const createdService = await this.adapterOfServices.createService(newService)
    const updatedServices = addedService(createdService, this.store.getters['services/services'])
    this.store.dispatch('services/createNewService', updatedServices)
    return createdService
  }

  async selectService(service) {
    this.store.dispatch('services/changeSelectedService', service)
  }

  async getSelectedService() {
    return this.store.getters['services/selectedService']
  }

  async cancelSelectedService(id) {
    const services = this.store.getters['services/services']
    const updatedServices = id === -1 ? removedNewService(services) : null
    this.store.dispatch('services/cancelSelectedService', updatedServices)
  }

  async editSelectedService(params) {
    const selectedService = this.store.getters['services/selectedService']
    // console.log('selectedService', selectedService)
    selectedService[params.key] = params.value
    this.store.dispatch('services/editSelectedService', selectedService)
  }

  async isSaveServices(event) {
    this.store.dispatch('services/changeIsSaveData', event)
  }

  async saveService(editService) {
    this.store.commit('services/setIsSaveData', false)
    this.store.commit('services/setSelectedService', null)
    const editedService = await this.adapterOfServices.updateService(editService)
    const services = this.store.getters['services/services']
    const updatedServices = !isEmpty(editedService) ? updatedService(editedService, services) : services
    // console.log('updatedServices', updatedServices)
    this.store.dispatch('services/saveService', updatedServices)
    return editedService
  }

  async removeService(id) {
    const deletedSiteId = await this.adapterOfServices.deleteService(id)
    const services = this.store.getters['services/services']
    const updatedServices = deletedSiteId ? deletedService(deletedSiteId, services) : null
    this.store.dispatch('services/saveService', updatedServices)
  }

}

export default ServiceOfServices