import {
fork as e,
cancel as t,
delay as n,
spawn as i,
put as o,
select as r,
takeLeading as d,
getContext as l,
} from "redux-saga/effects"
import { getCoreBackend as a, getNetworkBackend as c } from "../../backend"
import { apiCall as y } from "../../api/core"
import { APP_CONTEXT_KEY as u } from "../constants"
import { apiSubscribeSaga as s } from "../lib"
import { taskErrorSaga as f } from "../error"
import {
setNetworkData as m,
setNetworkSettings as p,
setNetworkSettingsDefault as g,
loadNetworkSettings as S,
updateNetworkSettings as w,
getNetworkConfig as k,
getNetworkStatusState as D,
} from "./network.reducer"
import { calcNetworkStatus as T, isNetworkStatusChanged as v } from "./network.model"
import { userInfoNotification as h } from "../notification"
function* x() {
const { network: e } = yield l(u)
yield o(g(e.dhtSettings))
const t = a(),
n = yield y(t.getDHTSettings)
yield o(p(n))
}
function* H({ payload: e }) {
try {
const { concurrency: t, maxWindow: n, randomPunchInterval: i, connectionKeepAlive: r } = e,
d = a()
;(yield y(d.updateDHTSettings, "concurrency", t),
yield y(d.updateDHTSettings, "maxWindow", n),
yield y(d.updateDHTSettings, "randomPunchInterval", i),
yield y(d.updateDHTSettings, "connectionKeepAlive", r),
yield o(h({ message: "New values only in effect when Keet is restarted" })))
} catch (e) {
yield f("networkSettingsUpdateSaga", e)
}
}
export function* networkStatusSaga() {
const e = c()
let d = yield y(function () {
return e.query()
})
yield o(m(d))
let l = 0,
a = null
function* u() {
const e = yield r(D)
v(e, d) && (yield o(m(d)), (l = Date.now()))
}
try {
yield s(
[
function () {
return e.subscribe()
},
],
function* (e) {
d = e
const o = yield r(D)
if (T(o) !== T(d)) return (a?.isRunning() && (yield t(a)), void (yield u()))
a?.isRunning() ||
(a = yield i(function* () {
const { NETWORK_UPDATE_DURATION: e } = yield r(k),
t = l + e - Date.now()
;(t > 0 && (yield n(t)), yield u())
}))
},
{ onError: (e) => f("networkStatusSaga", e) },
)
} finally {
a?.isRunning() && (yield t(a))
}
}
export function* networkSaga() {
;(yield e(networkStatusSaga), yield d(S, x), yield d(w, H))
}