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


function* authorize(username, password, replace) {
    try {
        const user = yield call(fetch, username, password);
        if (user && user.username && user.token) {
            user.authorities = user.authorities ? user.authorities.split(',').reduce((s,a)=>{s[a]=a; return s},{}) : {};
            sessionStorage.setItem('user', JSON.stringify({
                time: Date.now(),
                data: user
            }));
            yield put({type: 'LOGIN_SUCCESS', user});
            replace('/');
        } else {
            throw 'Server is Error: Token is invalid';
        }
    } catch (err) {
        console.error(err);
        message.error(err);
        yield put({type: 'LOGIN_ERROR', err})
    }
}

function* loginFlow() {
    while (true) {
        const {username, password, replace} = yield take('LOGIN_REQUEST');
        if (username && password) {
            yield fork(authorize, username, password, replace);
        }
        yield take(['LOGOUT', 'LOGIN_ERROR']);
        sessionStorage.clear();
        replace('/login');
    }
}


export default function*() {
    const ID = 'USER';
    yield fork(loginFlow);

    yield fork(watchIndex(ID, fetchList));
    yield fork(watchShow(ID, fetchItem));
    yield fork(watchEdit(ID, updateItem));

    yield fork(watch('CREATE_USER', create, '注册'));
    yield fork(watch('MODIFY_USER_PASSWORD', modifyPassword, '修改密码'));

}

