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

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* getList(query) {
    try {
        const {users, total} = yield call(fetchList, query);
        yield put({
            type: 'FETCH_USER_LIST_SUCCESS',
            items: users,
            total
        });
    } catch (err) {
        console.log(err);
        message.error(err);
        yield put({type: 'FETCH_USER_LIST_FAILED', err});
    }
}

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

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

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

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

function* watchMidfiyItem(){
    while(true){
        const {data} = yield take('UPDATE_USER_ITEM');
        yield fork(modifyItem, data);
    }
}


export default function*() {
    yield fork(loginFlow);
    yield fork(watchAddItem);
    yield fork(watchList);
    yield fork(watchItem);
    yield fork(watchMidfiyItem);
}

