import { blockUI, unblockUI } from './index.js';

import {
    getEmailAvailability,
    getNomAvailaibility,
    loginUser,
    registerNewUser,
} from '../api/profile.js';

import {
    DO_LOGOUT,
    LOGIN_FAILURE,
    LOGIN_SUCCESS,
    PROFILE_EMAIL_AVAILABLE,
    PROFILE_NOM_AVAILABLE,
    REGISTRATION_FAILURE,
    REGISTRATION_SUCCESS,
    UNSET_AUTH,
    UNSET_PROFILE,
    UPDATE_PROFILE,
} from '../constants/actionTypes.js';

const isValidEmail = (payload) => ({
    type: PROFILE_EMAIL_AVAILABLE,
    payload,
});

const isValidNom = (payload) => ({
    type: PROFILE_NOM_AVAILABLE,
    payload,
});

const loginFailure = (payload) => ({
    type: LOGIN_FAILURE,
    payload,
});

const loginSuccess = (payload) => ({
    type: LOGIN_SUCCESS,
    payload,
});

const logoutUser = () => ({
    type: DO_LOGOUT,
});

const registrationFailure = (payload) => ({
    type: REGISTRATION_FAILURE,
    payload,
});

const registrationSuccess = (payload) => ({
    type: REGISTRATION_SUCCESS,
    payload,
});

const unsetAuth = () => ({
    type: UNSET_AUTH,
});

const unsetProfile = () => ({
    type: UNSET_PROFILE,
});

const updateProfile = (profile) => ({
    type: UPDATE_PROFILE,
    payload: profile,
});

export const checkEmailAvailability = (email) => (dispatch) => {};

export const checkNomAvailability = (nomDeBid) => (dispatch) => {};

export const login = (username, password) => (dispatch) => {
    dispatch(blockUI());
    loginUser(username, password)
        .then((result) => {
            dispatch(loginSuccess(result));
        })
        .catch((err) => dispatch(loginFailure(err)));
};

export const logout = () => (dispatch) => {
    dispatch(unsetProfile());
    dispatch(unsetAuth());
    dispatch(logoutUser());
};

// USER REGISTRATION
const handleRegistrationSuccess = (user) => (dispatch) => {
    dispatch(unblockUI());
    dispatch(registrationSuccess());
    dispatch(loginSuccess(user));
};

const handleRegistrationFailure = (error) => (dispatch) => {
    dispatch(unblockUI());
    dispatch(registrationFailure(error));
};

export const registerUser = (user) => (dispatch) => {
    dispatch(blockUI());
    registerNewUser(user)
        .then((user) => dispatch(handleRegistrationSuccess(user)))
        .catch((err) => dispatch(handleRegistrationFailure(err)));
};

// FACEBOOK
export const facebookLoginSuccess = (result) => (dispatch) => {
    console.log('facebookLoginSuccess', result);
    dispatch(facebookLoginSuccess(result));
};

// LOGIN SERVICES COMMON ACTIONS
export const serviceRegistrationError = (error) => (dispatch) => {};

export const serviceRegistrationCanceled = () => (dispatch) => {};
