import { deepDiff as e } from "../lib/object"
const t = (e, t = 1e3) => Math.ceil(e * t) / t
export const loggerMiddleware =
({
enabled: s = !0,
logTs: o = !1,
logPerformance: a = !0,
logState: n = !1,
logPayload: r = !0,
filterActions: i = ["stats/setStatsData", "member/subscribe-cmd", "member/unsubscribe-cmd"],
filterActionsByPrefix: l = ["stats/"],
} = {}) =>
(c) => {
const m = []
let p = []
return s
? (s) => (h) => {
if (i.includes(h.type) || l.some((e) => h.type.startsWith(e))) return s(h)
const u = m.length,
d = {
action: h,
childrenTime: 0,
depth: u,
stateNext: null,
statePrev: null,
time: 0,
ts: Date.now(),
}
;(p.push(() =>
(({
action: s,
childrenTime: i,
depth: l,
stateNext: c,
statePrev: m,
time: p,
ts: h,
}) => {
const { type: u, payload: d } = s,
f = []
let g = null
if (
(o && f.push(h),
f.push(" ".repeat(l) + (l > 0 ? "└─" : "")),
f.push(u),
a &&
(i > 0
? f.push(`selfTime=${t(p - i)} childrenTime=${t(i)}`)
: f.push(`time=${t(p)}`)),
r && (g = { ...g, payload: d }),
n)
)
if (m === c) g = { ...g, state: c }
else {
const t = e(m, c)
g = { ...g, diff: t, statePrev: m, stateNext: c }
}
const b = f.join(" ")
g ? console.log(b, g) : console.log(b)
})(d),
),
m.push(d),
(d.statePrev = c.getState()))
const f = performance.now(),
g = s(h),
b = performance.now()
return (
(d.time = b - f),
(d.stateNext = c.getState()),
u > 0 && (m[u - 1].childrenTime += d.time),
m.pop(),
0 === u && (p.forEach((e) => e()), (p = [])),
g
)
}
: (e) => (t) => e(t)
}