import { call, put } from 'redux-saga/effects';
import { get } from 'services/requests';
import { handleError } from 'modules/error-handler';
import * as actions from 'lib/redux/actions/paginator-actions';
import omit from 'lodash/omit';

export function* fetchPaginatedContent(action): Generator {
	try {
		const res: Record<string, any> = yield call(() => get({
			url: action.url
		}));
		switch (action.entity) {
		case 'ads':
			yield put(actions.fetchedPaginatedContent({ ads: res.data, status: { ads: { fetching: false, error: false } } }));
			break;
		case 'shops':
			yield put(actions.fetchedPaginatedContent({ shops: res.data, status: { shops: { fetching: false, error: false } } }));
			break;
		case 'news':
			yield put(actions.fetchedPaginatedContent({ news: res.data, status: { news: { fetching: false, error: false } } }));
			break;
		case 'news/t':
			yield put(actions.fetchedPaginatedContent({ news: res.data, status: { news: { fetching: false, error: false } } }));
			break;
		case 'news/c':
			yield put(actions.fetchedPaginatedContent({ news: res.data, status: { news: { fetching: false, error: false } } }));
			break;
		default:
			yield put(actions.fetchedPaginatedContent({ ads: res.data.ads, model: omit(res.data, 'ads'), status: { ads: { fetching: false, error: false } } }));
		}
	}
	catch (error) {
		const status = {};
		if (!action.entity) status['ads'] = { fetching: false, error: true };
		status[action.entity] = { fetching: false, error: true };
		yield put(actions.failedFetchPaginatedContent({ error: error.message, status: status }));

		handleError(error);
	}
}

