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

const updatedSite = (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 removedNewSite = (sites) => {
  if (sites.length > 0) {
    const firstSite = sites[0]
    const isNewSite = firstSite.id === -1
    sites = isNewSite ? sites.slice(1) : sites
    return sites
  }
}

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

const addedNewRoute = (selectedSite, routes) => {
  let newRoute = routes.find((route) => route.action === 'create')
  if (newRoute) { 
    newRoute = {...newRoute, server_id: selectedSite.id}
    const withoutNewRoute = routes.filter(route => route.action !== 'create')
    return [newRoute, ...withoutNewRoute]
  }
}

const updatedRoute = (updatedRoute, routes) => {
  return routes.reduce((acc, cur) => {
    if (cur.id === updatedRoute.id) {
      return  [...acc, {
        ...cur,
        ...updatedRoute,
        action: updatedRoute.action === "create" ? "create" : "update"
      }]
    }
    return [...acc, cur]
  }, [])
}

const deletedRoute = (deletedRouteId, routes) => {
  return routes.reduce((acc, cur) => {
    if (cur.id !== deletedRouteId) return [...acc, cur]
    if (cur.action === "create") return acc
    return  [...acc, {
      ...cur,
      action: "remove"
    }]
  }, [])
}

const sortedRoutes = (routes) => {
  return routes.sort(({updated_at: a}, {updated_at: b}) => new Date(b).valueOf() - new Date(a).valueOf())
}

export { addedSite, updatedSite, removedNewSite, deletedSite, addedNewRoute, updatedRoute, sortedRoutes, deletedRoute }