import {
select as e,
fork as r,
put as o,
take as t,
race as i,
getContext as d,
} from "redux-saga/effects"
import { getRecentRoomsApi as n } from "../../../api/core"
import { taskErrorSaga as a } from "../../error"
import {
TOURS as l,
UI_PANEL as u,
getUITour as y,
toggleUIPanel as c,
tourFinish as p,
tourStart as s,
} from "../../ui-desktop"
import {
PREFERENCES as m,
getPreferencesTourComplete as f,
preferenceUpdateTask as g,
} from "../../preferences"
import { chatInit as S } from "../../chat"
import { setPairingRoom as T } from "../../room"
import {
addIdentityInvitedDevice as E,
getCreateUsernameStatus as F,
getHasIdentityUsername as R,
} from "../../identity/identity.reducer"
import { IDENTITY_USERNAME_SAVE_STATUS as h } from "../../identity"
import { ENV_CONTEXT_KEY as O } from "../../constants"
export function* updateTourCompletePreferences({ tour: r, value: o }) {
const t = yield e(f)
yield g(m.TOUR_COMPLETE, { ...t, [r]: o })
}
export function* onboardingTourSaga() {
const r = l.ONBOARDING
try {
const { rooms: d } = yield* n({ limit: 1 })
if (d.length > 0) return void (yield updateTourCompletePreferences({ tour: r, value: !0 }))
yield o(s(r))
const [a] = yield i([t(p), t(T), t(S), t(E)])
if (a) return
;(yield e(y)) === r && (yield o(p(r)))
} catch (e) {
yield a("onboardingTourSaga", e)
}
}
export function* addFriendsTourSaga() {
const e = l.ADD_FRIENDS
try {
const { rooms: r } = yield* n({ limit: 1 })
if (r.length > 0) return void (yield updateTourCompletePreferences({ tour: e, value: !0 }))
} catch (e) {
yield a("addFriendsTourSaga", e)
}
;(yield t(S), yield o(s(e)))
}
export function* profileTourSaga() {
const r = l.PROFILE,
{ username: i } = yield d(O)
yield t((e) => c.match(e) && e.payload.key === u.PROFILE)
const n = yield e(R),
a = yield e(F)
!n && a !== h.RESERVING && i?.registerEnabled && (yield o(s(r)))
}
export function* tourFinishListenerSaga() {
for (;;) {
const { payload: e } = yield t(p)
try {
yield updateTourCompletePreferences({ tour: e, value: !0 })
} catch (e) {
yield a("update tour complete preferences", e)
}
}
}
export function* toursSaga() {
const o = yield e(f)
let t
;(o?.[l.ONBOARDING] || ((t = !0), yield r(onboardingTourSaga)),
o?.[l.ADD_FRIENDS] || ((t = !0), yield r(addFriendsTourSaga)),
o?.[l.PROFILE] || ((t = !0), yield r(profileTourSaga)),
t && (yield tourFinishListenerSaga()))
}