import React from 'react';
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/districts-actions';
import { notification, Button } from 'antd';
import { subdomain } from '@routes/routes';



export function* fetchDistricts() {
	try {
		const res = yield call(() => get({
			url: Api.districts
		}));

		// dispatch a success action to the store with the fetched districts
		yield put(actions.fetchedDistricts({ data: res.data }));

	}
	catch (error) {
		// dispatch a failure action to the store with the error
		yield put(actions.failedFetchDistricts({ error: error.message }));

		handleError(error);
	}
}


export function* fetchDistrict(action) {
	try {
		const res = yield call(() => get({
			url: Api.districts + '/' + action.slug
		}));

		// dispatch a success action to the store with the fetched districts
		yield put(actions.fetchedDistrict({ data: res.data }));


		const btn = (
			<a href={`//${res.data.slug}.${process.env.APP_HOST + '/' + window.location.pathname}`} className="btn mtn-md btn-success">
				Change District
			</a>
		);
		if (subdomain != res.data.slug)
			notification.open({
				message: 'Change District?',
				placement: 'bottomRight',
				duration: 0,
				description:
					'Click \'Change District\' to switch to ' + res.data.name,
				btn,
				onClose: close,
			});

	}
	catch (error) {
		// dispatch a failure action to the store with the error
		yield put(actions.failedFetchDistrict({ error: error.message }));

		handleError(error);
	}
}



export function* fetchDistrictClassifiedAds(action) {
	try {
		const res = yield call(() => get({
			url: Api.districts + '/' + action.district_slug + '/' + action.classified_slug
		}));

		// dispatch a success action to the store with the fetched districts
		yield put(actions.fetchedDistrictClassifiedAds({ data: res.data.ads }));

	}
	catch (error) {
		// dispatch a failure action to the store with the error
		yield put(actions.failedFetchDistrictClassifiedAds({ error: error.message }));

		handleError(error);
	}
}
