const addedService = (addedSite, sites) => {
  const sitesWithoutNewSite = removedNewService(sites)
  return [addedSite,...sitesWithoutNewSite]
}

const updatedService = (updatedSite, sites) => {
  if (updatedSite.id) {
    const editIdx = sites.findIndex(service => service.id === updatedSite.id)
    const beforeEdit = sites.slice(0, editIdx)
    const afterEdit = sites.slice(editIdx + 1)
    const withEdit = [...beforeEdit, updatedSite]
    return [...withEdit, ...afterEdit]
  }
}

const removedNewService = (sites) => {
  if (sites.length > 0) {
    const firstSite = sites[0]
    const isNewSite = firstSite.id === -1
    sites = isNewSite ? sites.slice(1) : sites
    return sites
  }
}

const deletedService = (deletedSiteId, sites) => {
  if (deletedSiteId) {
    const deleteIdx = sites.findIndex(service => service.id === deletedSiteId)
    return sites.slice(0, deleteIdx).concat(sites.slice(deleteIdx + 1))
  }
}

export { addedService, updatedService, removedNewService, deletedService }