import { actionLoginNetworkError, actionLoginNetworkErrorReset } from '../Redux/network_reducer';
import { actionPromise } from '../Redux/promise_reducer';
import {actionLogin, gql} from './action_login';

export const actionRegistrations = (login, password) => async (dispatch) => {
    console.log(login, password)
    let result = await dispatch(actionPromise('Registration', gql(`mutation newUser($loginStr: String!, $passwordStr: String!){
        createUser(login: $loginStr, password: $passwordStr){
            _id
            login
            }
        }`,
        {
            "loginStr": login,
            "passwordStr": password
        })
    )
    )
    if(result?.data?.createUser===null) {
        //  такой пользователь есть
    } else {
        if (result?.data?.createUser?._id) {
            console.log('Registered successfull')
            dispatch(actionLogin(login, password))
        } else {
            console.log("Registration failed")
            dispatch(actionLoginNetworkError())
            setTimeout(() => { actionLoginNetworkErrorReset() }, 5000)
        }
    }
}