import { Action } from 'lib/types/interfaces';
import { select, put } from 'redux-saga/effects';
import * as actions from 'lib/redux/actions/eha-actions';
import isEmpty from 'lodash/isEmpty';



export function* embedAd(action: Action) {
	try {
		const getMaker = state => state.eha;
		let eha = yield select(getMaker);

		if (isEmpty(eha)) {
			eha = {};
		}

		if (!eha[action.key]) {
			if (process.env.NODE_ENV == 'production') {
				(window['adsbygoogle'] = window['adsbygoogle'] || []).push({});
			}
			eha[action.key] = action.key;
		}
		yield put(actions.embededAd({ data: eha }));
	}
	catch (error) {
		yield put(actions.failedEmbedAd({ error }));
	}
}


export function* removeEmbedFromCache(action) {
	try {
		const getState = state => state.eha;

		let eha = yield select(getState);
		if (isEmpty(eha)) eha = {};

		if (eha[action.localKey]) {
			eha[action.localKey] = null;
			window['adsbygoogle']?.pop;
		}
		yield put(actions.embededAd({ data: eha }));
	}
	catch (error) {
		// 
	}
}