import { select as e, call as r, put as o, all as t } from "redux-saga/effects"
import { taskErrorSaga as s } from "../../error"
import { getChatCurrentRoomId as a } from "../init"
import {
isMessageChangedExcludeGrouping as i,
chatMessagesTransform as m,
updateChatLastMessage as n,
} from "../message"
import { getChatUnreadLastSeenSeq as d, getMessageUnread as l } from "../unread"
import { getChatLastSeenMessageSeq as c, getChatMessageCount as g } from "../list-view"
import { getChatLastMessage as f } from "./last-message.selector"
import {
getMemberItemById as p,
parseMemberResponse as u,
setMemberProfile as y,
} from "../../member"
import { apiCall as h } from "../../../api/core"
import { getCoreBackend as M } from "../../../backend"
export function* chatSetLastMessage({
roomId: g,
ignoreBlocked: I,
hasPeerSeen: b,
lastMessage: S,
}) {
try {
const s = yield r(d, { roomId: g }),
[L, k] = yield t([e(a), e(c)])
let v = s
L === g && (v = k)
const [C] = yield m({ roomId: g, ignoreBlocked: I, coreEvents: [S] }),
[$] = C
if ($) {
const { unread: r, message: t, peerNotSeen: s } = yield e(f, g),
a = l($, v),
m = b && $.local && !S.read,
d = s !== m,
c = i(t, $)
if (t && !c && r === a && !d) return
if ($.targetMemberId) {
let r = yield e(p(g, $.targetMemberId))
if (!r) {
const e = M()
;((r = yield h(e.getMember, g, $.targetMemberId)),
(r = u(r)),
yield o(y({ roomId: g, profile: r })))
}
}
yield o(
n({ roomId: g, ignoreBlocked: I, message: $, unread: a, prevSeen: v, peerNotSeen: m }),
)
}
} catch (e) {
yield s("chatSetLastMessage", e)
}
}
export function* chatLastMessageCountCheckDebugLog({ roomId: r }) {
const { message: o, unread: t, prevSeen: a } = yield e(f, r)
if (o) {
const r = o.seq + 1,
i = yield e(g)
if (i < r) {
const e = `ChatLength=${i} smaller then lastMessage.seq=${o.seq}\n unread=${t} prevSeen=${a}`
yield s("chatLastMessageCountCheckDebugLog", e, { logWarn: !0 })
}
}
}