import { all, takeLatest, call, put } from "@redux-saga/core/effects";
import { attemptFetchExchange, attemptValidateExchange } from "../../request/exchangeRequest";
import { EXCHANGE_FETCH, EXCHANGE_VALIDATE_FETCH } from "../actions/exchange/exchangeActionConstants";
import { fetchExchangeError, fetchExchangeSuccess, setExchange, validateExchangeError, validateExchangeSuccess } from "../actions/exchange/exchangeActions";

function* fetchExchange(payload) {
    try {
        const data = yield call(attemptFetchExchange, payload.payload);
        yield put(setExchange(data.data));
        yield put(fetchExchangeSuccess());
    }
    catch (e) {
        yield put(fetchExchangeError());
        console.log(e);
    }
}

function* validateExchange(payload) {
    try {
        yield call(attemptValidateExchange, payload.payload);
        const data = yield call(attemptFetchExchange, payload.payload);
        yield put(setExchange(data.data));
        yield put(validateExchangeSuccess());
    }
    catch(e) {
        yield put(validateExchangeError());
        console.log(e);
    }
}

export default function* exchangeSaga() {
    yield all([
        takeLatest(EXCHANGE_FETCH, fetchExchange),
        takeLatest(EXCHANGE_VALIDATE_FETCH, validateExchange)
    ]);
}