import { call, put } from 'redux-saga/effects';
import { get } from 'services/requests';
import { Api } from 'routes/Api';
import { handleError } from 'modules/error-handler';
import * as actions from 'lib/redux/actions/rankings-actions';


export function* fetchRankings(): Generator {
	try {
		const res: Record<string, any> = yield call(() => get({
			url: Api.rankings
		}));

		yield put(actions.fetchedRankings({ data: res.data }));

	}
	catch (error) {
		yield put(actions.failedFetchRankings({ error: error.message }));

		handleError(error);
	}
}



export function* fetchRankingsTaCat(action): Generator {
	try {
		let res;

		if (action.sorter) res = yield call(() => get({
			url: `${Api.rankings}/${action.sorter}/${action.slug}`
		}));
		else res = yield call(() => get({
			url: Api.rankings
		}));
		yield put(actions.fetchedRankingsTaCat({ data: res.data }));
	}
	catch (error) {
		yield put(actions.failedFetchRankingsTaCat({ error: error.message }));

		handleError(error);
	}
}




export function* fetchRanking(action): Generator {
	try {
		const res: Record<string, any> = yield call(() => get({
			url: Api.rankings + '/' + action.slug
		}));

		yield put(actions.fetchedRanking({ data: res.data }));

	}
	catch (error) {
		yield put(actions.failedFetchRanking({ error: error.message }));

		handleError(error);
	}
}


