You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.8 KiB

import React from 'react';
import useAppState from './useAppState';
import ApiHelper from '../helpers/ApiHelper';
import { useEffectOnce } from '../helpers/Hooks';
export const AppContext = React.createContext();
const AppContextProvider = props => {
const [state, dispatch, updatedState] = useAppState();
const Api = new ApiHelper({ state });
const addWallet = address => {
// @TODO check if valid addy
const storedWallets = JSON.parse(localStorage.getItem('pool.wowne.ro')) || {};
if (!storedWallets[address]) {
getMinerStats(address);
setMinerIntervals(address);
}
};
const getMinerStats = address => {
const storedWallets = JSON.parse(localStorage.getItem('pool.wowne.ro')) || {};
Api.getMinerStats(address)
.then(res => {
storedWallets[address] = res;
localStorage.setItem('pool.wowne.ro', JSON.stringify(storedWallets));
dispatch({ type: 'UPDATE_WALLETS' });
});
};
const getNetworkStats = () => {
return Api.getNetworkStats()
.then(networkStats => {
dispatch({ type: 'UPDATE_NETWORK_STATS', networkStats });
});
};
const getPoolConfig = () => {
return Api.getPoolConfig()
.then(config => {
dispatch({ type: 'UPDATE_POOL_CONFIG', config });
});
};
const getPoolStats = () => {
return Api.getPoolStats()
.then(stats => {
dispatch({ type: 'UPDATE_POOL_STATS', stats });
});
};
const actions = {
addWallet,
};
const setIntervals = () => new Promise((resolve, _) => {
const { appSettings } = state;
const intervals = [
{ fn: getPoolStats, time: appSettings.poolStatsUpdateInterval },
{ fn: getNetworkStats, time: appSettings.networkStatsUpdateInterval },
];
dispatch({ type: 'SET_INTERVALS', intervals });
resolve();
});
const setMinerIntervals = wallet => {
const { appSettings } = updatedState.current;
const intervals = [
{ fn: getMinerStats, params: wallet, time: appSettings.minerStatsUpdateInterval },
]
dispatch({ type: 'SET_INTERVALS', intervals });
}
useEffectOnce(() => {
dispatch({ type: 'UPDATE_WALLETS' });
getPoolConfig().then(() =>
getPoolStats().then(() =>
getNetworkStats().then(() => {
setIntervals().then(() => {
// app ready now
if (updatedState.current.user.wallets) {
Object.keys(updatedState.current.user.wallets).forEach(wallet => {
getMinerStats(wallet);
setMinerIntervals(wallet);
});
}
dispatch({ type: 'APP_LOADED', appLoaded: true });
});
})
)
);
})
return (
<AppContext.Provider value={{ state, actions }}>
{state.appSettings.appLoaded && props.children}
</AppContext.Provider>
)
};
export default AppContextProvider;