import {takeLatest} from 'redux-saga';
import {take, call, put, fork, cancel} from 'redux-saga/effects';
import {fetch, clear, save} 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 (error) {
        yield put({type: 'LOGIN_ERROR', error})
    }
}

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);
    }
}

export default function* () {
    yield fork(loginFlow);
}

