import {takeLatest} from 'redux-saga';
import {take, call, put, fork, cancel, race } from 'redux-saga/effects';
import {fetch, clear, save, create, fetchList, fetchItem, updateItem} from '../services/user';
import {message} from 'antd';
import {watchIndex, watchShow, watchCreate} from './RESTful';


function* authorize(username, password, push) {
    try {
        const user = yield call(fetch, username, password);
        console.log(user);
        yield put({type: 'LOGIN_SUCCESS', user});
        console.log('login ok');
        push('/');
    } catch (err) {
        yield put({type: 'LOGIN_ERROR', err})
    }
}

function* loginFlow() {
    while (true) {
        console.log('login flow');
        const {username, password, push} = yield take('LOGIN_REQUEST');
        yield fork(authorize, username, password, push);
        yield take(['LOGOUT', 'LOGIN_ERROR']);
        yield call(clear);
    }
}

function* addItem(data) {
    try {
        yield call(create, data);
        yield put({type: 'CREATE_USER_ITEM_SUCCESS'});
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({type: 'CREATE_USER_ITEM_FAILED', err});
    }
}

function* watchAddItem() {
    while (true) {
        const {data} = yield take('CREATE_USER_ITEM');
        yield fork(addItem, data);
    }
}


function* modifyItem(item) {
    try {
        yield call(updateItem, item);
        yield put({
            type: 'UPDATE_USER_ITEM_SUCCESS',
            item
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield  put({
            type: 'UPDATE_USER_ITEM_FAILED',
            err
        });
    }
}

function* watchMidfiyItem(){
    while (true) {
        yield take('UPDATE_USER');
        yield put({
            type: 'UPDATE_USER_START'
        });
        const {data} = yield race({
            data: take('UPDATE_USER_ITEM'),
            canceled: take('CANCEL_UPDATE_USER')
        });

        if (data && data.item) {
            yield fork(modifyItem, data.item);
        }else{
            yield put({
                type: 'UPDATE_USER_END'
            });
        }
    }
}


export default function*() {
    yield fork(loginFlow);
    yield fork(watchCreate('USER', create));
    yield fork(watchIndex('USER', fetchList));
    yield fork(watchShow('USER', fetchItem));
    yield fork(watchMidfiyItem);
}

