import {actionAuthLogin, actionPromise} from "../reducers";
import {call, put, takeEvery} from "redux-saga/effects";
import {promiseWorker} from "../reducers/promiseReducer";
import {actionPlaylistFindByOwner, gql} from "./index";
import {actionAboutMe,actionUserFind,actionFindMyTracks} from "./index";

export const actionLogin = (login, password) => {
    return actionPromise(
        "login",
        gql(
            `query log($login:String!, $password:String!) {
    login(login:$login, password:$password)
    }`,
            {login, password }
        )
    );
};


export const actionFullLogin = (login, password) =>
    ({type:'FULL_LOGIN', login, password})

export function* fullLoginWorker (action) {
    const {login, password} = action

    let token = yield call(promiseWorker, actionLogin(login, password)) //dispatch(actionLogin(login, password));
    if (token) {
        yield put(actionAuthLogin(token));
        yield put(actionUserFind())
        yield put(actionPlaylistFindByOwner())
        yield put(actionAboutMe())
    }
}

export function* fullLoginWatcher() {
    yield takeEvery ('FULL_LOGIN',fullLoginWorker)
}



export const actionFullReg = (login, password) =>
    ({type:'FULL_REG', login, password})

function* regWorker(action) {
    const {login, password} = action
    let regId = yield call(promiseWorker, actionReg(login, password))
    if (regId) {
        yield put(actionFullLogin(login, password))
    }
}

export function* regWatcher() {
    yield takeEvery('FULL_REG', regWorker)
}

export const actionReg = (login, password) => {
    return actionPromise(
        "reg",
        gql(
            `mutation reg($l: String!, $p: String!){
        createUser(login: $l, password:$p){
          _id login
        }
      }`,
            { l: login, p: password }
        )
    );
};