import { select as e, put as t, takeLatest as o, takeEvery as a } from "redux-saga/effects"
import { getCoreBackend as i } from "../../../backend"
import { apiCall as r } from "../../../api/core"
import { taskErrorSaga as d } from "../../error"
import { getChatConfig as n } from "../init"
import { CHAT_MESSAGE_REPORT_REACTION as c } from "../chat.constant"
import { getCoreId as m } from "../message"
import { getChatMessageCoreIdById as s } from "../list-view"
import {
askChatReactionMembersCmd as l,
reportChatMemberSuccess as p,
reportChatMessageSuccess as y,
setChatReactionMembers as f,
toggleReactionCmd as g,
} from "./chat-reaction.action"
import { getChatReactionsById as R } from "./chat-reaction.selector"
import { reloadMessagesCmd as h } from "../list-view/list-view-data.action"
import { getPreferencesNoChatRateLimit as I } from "../../preferences"
let b = []
export function* isSendReactionRateLimited() {
const { reactionRateLimit: t, reactionRateLimitInterval: o } = yield e(n)
if (yield e(I)) return !1
const a = Date.now() - o
return ((b = b.filter((e) => e > a)), b.length >= t || (b.push(Date.now()), !1))
}
export function* toggleReactionSaga(t, o) {
if (!(yield isSendReactionRateLimited()))
try {
const { text: a, messageId: d } = o.payload,
n = m(d),
{ mine: c } = yield e(R(d)),
s = i()
c.includes(a) ? yield r(s.removeReaction, t, n, a) : yield r(s.addReaction, t, n, a)
} catch (e) {
yield d("toggleReactionSaga", e)
}
}
export function* chatMessageReportHandler({ roomId: o, useLabelsFeature: a }, n) {
try {
const { messageId: d, memberId: m } = n.payload,
l = yield e((e) => s(e, d))
if (!l.deviceId) throw new Error("incompatible message id")
const p = i()
;(a ? yield r(p.addChatReport, o, l) : (yield r(p.addReaction, o, l, c), yield t(h())),
yield t(y({ messageId: d, memberId: m })))
} catch (e) {
yield d("chatMessageReportHandler", e)
}
}
export function* chatMemberReportHandler({ roomId: e }, o) {
try {
const { memberId: a } = o.payload,
d = i()
;(yield r(d.reportMember, e, a), yield t(p({ roomId: e, memberId: a })))
} catch (e) {
yield d("chatMemberReportHandler", e)
}
}
export function* chatReactionMemberLoadSaga({ roomId: e }, { payload: o }) {
const { messageId: a, id: n } = o,
c = i()
try {
const o = m(a),
i = (yield r(c.getLatestReactions, e, o, n))
.map((e) => e.sender)
.filter((e) => "string" == typeof e && !!e)
yield t(f({ id: n, messageId: a, memberIds: i }))
} catch (e) {
yield d("chatReactionMemberLoadSaga", e)
}
}
export function* chatReactionSaga({ roomId: e }) {
;(yield o(g, toggleReactionSaga, e), yield a(l, chatReactionMemberLoadSaga, { roomId: e }))
}