import {takeLatest} from 'redux-saga';
import {take, call, put, fork, cancel, select} from 'redux-saga/effects';
import {
    fetchList, fetchItem, pass,
} from '../services/remittance';
import {message} from 'antd';

function* getList(query) {
    try {
        const {total, list} = yield call(fetchList, query);
        yield put({
            type: 'FETCH_REMITTANCE_LIST_SUCCESS',
            total,
            items: list
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'FETCH_REMITTANCE_LIST_FAILED',
            err,
        });
    }
}

function* watchList() {
    while (true) {
        const {query} = yield take('FETCH_REMITTANCE_LIST');
        yield fork(getList, query);
    }
}

function* getItem(id) {
    try {
        const item = yield call(fetchItem, id);
        yield put({
            type: 'FETCH_REMITTANCE_ITEM_SUCCESS',
            item
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'FETCH_REMITTANCE_ITEM_FAILED',
            err
        });
    }
}

function* watchItem() {
    while (true) {
        const {id} = yield take('FETCH_REMITTANCE_ITEM');
        yield fork(getItem, id);
    }
}

function* passItem(item){
    try {
        yield call(pass, item);

        yield put({
            type: 'PASS_REMITTANCE_ITEM_SUCCESS',
            item
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({
            type: 'PASS_REMITTANCE_ITEM_FAILED',
            err
        });
    }
}
function* watchPassItem() {
    while (true) {
        const {data} = yield take('PASS_REMITTANCE_ITEM');
        yield fork(passItem, data);
    }
}


export default function*() {
    yield fork(watchList);
    yield fork(watchItem);
    yield fork(watchPassItem);
}
