import { call, put } from 'redux-saga/effects';
import { get, post } from './../../../services/requests';
import { get as get2 } from './../../../services/requests-v2';
import { rdr } from './../../../routes/routes';
import { Api } from './../../../routes/Api';
import { Swal } from './../../../lib/swal/swal';
import { handleError } from './../../../modules/error-handler';
import * as actions from './../actions/classifieds-actions';
import api from '@routes/api-v2';



export function* fetchClassify(action) {
	try {
		const res = yield call(() => get2({
			url: api('classifieds.show', {slug: action.data.slug}, action.options)
		}));


		// dispatch a success action to the store with the fetched classifieds
		yield put(actions.fetchedClassify({ data: res.data }));

	}
	catch (error) {
		// dispatch a failure action to the store with the error
		yield put(actions.failedFetchClassify({ error: error.message }));

		handleError(error);
	}
}

export function* fetchClassifieds(action) {
	try {
		const res = yield call(() =>
			get2({
				url: api('classifieds.index', null, action.options),
			}),
		);

		yield put(actions.fetchedClassifieds({ data: res.data,
			pagination: res.pagination,
		}));

	}
	catch (error) {
		// dispatch a failure action to the store with the error
		yield put(actions.failedFetchClassifieds({ error: error.message }));

		handleError(error);
	}
}



export function* createClassified(action) {
	try {

		const res = yield call(() => post({
			url: Api.createClassified,
			data: action.payload,
			options: {
				headers: {
					'Content-Type': 'multipart/form-data',
				}
			}
		}));

		yield put(actions.createdClassified({ data: res.data }));

		Swal.fire({
			title: 'Success',
			text: 'New Classified Created!.',
			imageUrl: Api.root+'/ashantiwebmedia/classifieds/'+res.data.picture,
			imageWidth: 400,
			imageHeight: 200,
			imageAlt: res.data.name,
		}).then(() => rdr('/'));

	}
	catch (error) {
		// dispatch a failure action to the store with the error

		// handle laravel validation errors
		if(error.response.status == 422) {
			return yield put(actions.failedCreateClassified({ error: error.response.data.errors }));
		}

		yield put(actions.failedCreateClassified({ error: error.message }));
		return handleError(error);
	}
}
