import { select as o, put as r, take as e, race as m } from "redux-saga/effects"
import { getCoreBackend as i } from "../../../backend"
import { apiCall as t } from "../../../api/core"
import { callLeave as d, getCallStatus as l, isCallJoinedMode as c } from "../../call"
import { taskErrorSaga as f } from "../../error"
import {
switchRoomSubmit as a,
closeRoomSubmit as n,
isRoomRemovedFromRecents as y,
} from "../room.action"
import {
leaveRoomConfirmationRequired as p,
leaveRoomConfirmForce as s,
leaveRoomRejectForce as u,
leaveRoomCleanup as I,
leaveRoomSuccessEvent as b,
} from "./room-joint.reducer"
import { EMPTY_ROOM_ID as g } from "../room.constant"
import { getRoomIsDm as v } from "../room.selector"
import { canIndex as h, getMyMember as x } from "../../member"
import { getRoomListAllIds as L } from "../list"
import { getDmMemberByRoomId as R, resetDmContact as S } from "../dm/room-dm.reducer"
export function* roomLeaveHandler({ roomId: a, currentCallRoomId: n = g }) {
if (a)
try {
const f = i(),
I = yield o(v(a)),
g = yield o(l)
n && a === n && c(g) && (yield r(d()))
const L = yield o(x(a)),
j = (yield t(f.getModerators, a)).filter((o) => h(o.capabilities)).map((o) => o.memberId)
if (1 === j.length && j[0] === L?.memberId && !I) {
yield r(p())
const o = yield e([s, u])
if (u.match(o)) return
}
if ((yield m([t(f.leaveRoom, a), e(y(a))]), I)) {
const e = yield o(R(a))
yield r(S({ memberId: e, roomId: a }))
}
yield r(b(a))
} catch (o) {
yield f("roomLeaving", o)
} finally {
yield r(I())
}
}
export function* roomLeaveSuccessSaga({ roomId: e, currentRoomId: m }) {
if (e && e === m) {
const m = (yield o(L)).find((o) => o !== e) || g
m ? yield r(a({ roomId: m })) : yield r(n())
}
}