import { put as e, select as t } from "redux-saga/effects"
import { getCoreBackend as r } from "../../../backend"
import { apiCall as o } from "../../../api/core"
import { apiSubscribeSaga as n } from "../../lib"
import { taskErrorSaga as a } from "../../error"
import { LAST_MESSAGE_ALL_SEEN_SEQ as i } from "../chat.constant"
import {
chatMessageJumpToSeqCmd as c,
getChatListViewHistory as d,
getChatMessagesInView as m,
getChatLastSeenMessageSeq as s,
} from "../list-view"
import { chatUnreadSyncData as l } from "./chat-unread.action"
export function* getChatUnreadLastSeenSeq({ roomId: e }) {
const t = r(),
n = yield o(t.getUnreadAnchor, e)
return n?.length ? Math.max(n.length - 1, 0) : i
}
export function* chatUpdateLastSeenMessage({ roomId: e }) {
try {
const n = yield t(s),
a = r(),
i = yield o(a.getUnreadAnchor, e),
c = Math.max(i?.length ? i.length - 1 : 0, 0)
if (c && c >= n) return
yield o(a.setUnreadAnchor, e, n + 1)
} catch (e) {
yield a("chatUpdateLastSeenMessage", e)
}
}
export function* chatSubscribeUnreadSaga({ roomId: o, autoscroll: a }) {
yield n([r().subscribeUnreadAnchor, o], function* (r) {
if (!r || !Number.isInteger(r.length)) return
const n = yield t(s),
i = Math.max(r.length - 1, 0)
if ((i !== n && (yield e(l({ roomId: o, seq: i }))), !a)) return
const h = yield t(d),
f = yield t(m)
h && i > f.bottom && (yield e(c({ seq: i })))
})
}