(ns iol-ion.tx.reset-rels
  (:require [datomic.api :as dc]))

(defn reset-rels [db e a vs]
  (assert (every? :db/id vs) (format "In order to reset attribute %s, every value must have :db/id" a))
  (let [ids                             (when-not (string? e)
                      (->> (dc/q '[:find  ?z
                                   :in    $ ?e ?a
                                   :where [?e ?a ?z]]
                                 db e a)
                           (map first)))
        new-id-set                      (set (map :db/id vs))
        retract-ids                     (filter (complement new-id-set) ids)
        {is-component? :db/isComponent} (dc/pull db [:db/isComponent] a)
        new-rels                        (filter (complement (set ids)) (map :db/id vs))]
    (-> []
        (into (map (fn [i] (if is-component?
                             [:db/retractEntity i]
                             [:db/retract e a i ])) retract-ids))
        (into (map (fn [i] [:db/add e a i]) new-rels))
        (into (map (fn [i] [:upsert-entity i]) vs)))))
