import { debounce as e, put as r, select as a, takeEvery as t, take as o } from "redux-saga/effects"
import { getCoreBackend as i } from "../../../backend"
import { taskErrorSaga as c } from "../../error"
import { chatMessageJumpToCmd as s } from "../list-view"
import { getChatConfig as h } from "../init"
import {
chatMessageClickEvt as l,
sendChatMessageSubmit as n,
chatMessagesTransform as d,
} from "../message"
import {
chatSearchDisable as m,
chatSearchGoNextMsgCmd as y,
chatSearchGoPrevMsgCmd as p,
chatSearchInputEvt as f,
addChatSearchMessages as u,
setChatSearchTerms as S,
setChatSearchMessagesDone as g,
} from "./chat-search.action"
import { EMPTY_INDEX as I } from "./chat-search.constant"
import {
getChatSearchActiveId as x,
getChatSearchActiveIndex as F,
getChatSearchLive as M,
getChatSearchResultsCount as v,
getChatSearchTerms as C,
} from "./chat-search.selector"
import { isSearchTermsLimited as b } from "./chat-search.model"
import { apiSubscribeSaga as J } from "../../lib"
import { isEmpty as k } from "../../lib/array"
export function* chatSearchInputSaga(e) {
;(yield a(M)) && (yield r(S(e.payload.split(" "))))
}
export function* chatSearchMessagesSaga({ roomId: e }) {
const t = yield a(C)
k(t) ||
b(t) ||
(yield J(
[i().createChatSearchStream, e, t],
function* (a) {
const t = [a],
[o] = yield d({ roomId: e, ignoreBlocked: !0, coreEvents: t })
k(o) || (yield r(u(o)))
},
{
onError: (e) => c("chatSearchMessagesSaga", e),
onCleanup: function* ({ apiClose: e }) {
e && (yield r(g()))
},
},
))
}
export function* chatSearchActiveMessageHandler() {
if (!(yield a(M))) return
const e = yield a(x)
e && (yield r(s({ messageId: e, highlight: !0 })))
}
export function* chatSearchJumpFirstFound() {
const e = yield a(M),
t = yield a(v),
{ searchResultNoJumpCount: o } = yield a(h)
!e || !t || t > o || ((yield a(F)) === I && (yield r(y())))
}
export function* chatSearchSaga({ roomId: i }) {
try {
if (!(yield a(M))) return
const { searchFirstFounDelay: c, searchInputThrottle: s } = yield a(h)
;(yield e(s, f, chatSearchInputSaga),
yield t(S, chatSearchMessagesSaga, { roomId: i }),
yield t([l, y, p], chatSearchActiveMessageHandler),
yield e(c, u, chatSearchJumpFirstFound),
yield o(n),
yield r(m()))
} catch (e) {
yield c("chatSearchSaga", e)
}
}