import{watch as o}from"../support/observableUtils.js";import{checkArg as e}from"./checkArg.js";import{_generateChangeEvent as t}from"./collection.js";export function onEach(o,t,n){e("collection",o).isNotMissing(),e("eventType",t).isNotMissing().isNotEmpty(),e("callback",n).isNotMissing();const s=new Map;for(const e of o.toArray())s.set(e,e.on(t,n));const r=o.on("change",(o=>{for(const e of o.added)s.set(e,e.on(t,n));for(const e of o.removed){const o=s.get(e);o&&o.remove(),s.delete(e)}}));return{remove:()=>{r.remove(),s.forEach((o=>o.remove()))}}}export function onCollectionPropertyChange(n,s,r,i=!1){let c;e("obj",n).isNotMissing(),e("property",s).isNotMissing().isNotEmpty(),e("callback",r).isNotMissing();const f=s.split(".");let l=n;for(;l&&"object"==typeof l&&f.length;)l=l[f.shift()];l&&(c=l.on("change",r));const m=o(n,s,((o,e)=>{c&&(c.remove(),c=void 0),o&&(c=o.on("change",r));const n=t(e,o);if(n?.added.length||n?.removed.length||n?.moved.length)if("function"==typeof r)r(n);else{const o=r.deref();o?.(n)}}),{sync:i});return{remove:()=>{c&&c.remove(),m.remove()}}}export function onOnce(o,e,t){const n=o.on(e,(o=>{if("function"==typeof t)t(o);else{const e=t.deref();e?.(o)}n.remove()}));return n}