export const SHOW_LOGIN_DIALOG = 'SHOW_LOGIN_DIALOG';
export const HIDE_LOGIN_DIALOG = 'HIDE_LOGIN_DIALOG';


export const LOGOUT = 'LOGOUT'
export const AUTHENTICATION_PENDING = 'AUTHENTICATION_PENDING'
export const AUTHENTICATION_SUCCESS = 'AUTHENTICATION_SUCCESS'
export const AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR'

const URL = process.env.REACT_APP_SERVER

export function getShowLoginDialogAction() {
    return {
        type: SHOW_LOGIN_DIALOG
    }
}


export function getHideLoginDialogAction() {
    return {
        type: HIDE_LOGIN_DIALOG
    }
}

export function getLogoutAction() {
    return {
        type: LOGOUT
    }
}

export function getAuthenticationPendingAction() {
    return {
        type: AUTHENTICATION_PENDING
    }
}

export function getAuthenticationSuccessAction(userSession) {
    return {
        type: AUTHENTICATION_SUCCESS,
        user: userSession.user,
        accessToken: userSession.accessToken,
        isAdmin: userSession.isAdmin
    }
}

export function getAuthenticationErrorAction(error) {
    return {
        type: AUTHENTICATION_ERROR,
        error: error
    }
}


export function authenticateUser(userID, password) {
    return dispatch => {
        dispatch(getAuthenticationPendingAction());
        login(userID, password)
            .then(
                userSession => {
                    const action = getAuthenticationSuccessAction(userSession);
                    dispatch(action);
                },
                error => {
                    dispatch(getAuthenticationErrorAction(error));
                }
            )
            .catch(error => {
                dispatch(getAuthenticationErrorAction(error))
            })
    }
}

function login(userID, password) {
    const requestOptions = {
        method: 'GET',
        headers: { 'Authorization': 'Basic ' + btoa(userID + ":" + password) }
    };

    return fetch(URL + '/authenticate', requestOptions)
        .then(handleResponse)
        .then(userSession => {
            return userSession
        });
}

function handleResponse(response) {
    const authorizationHeader = response.headers.get("Authorization");
    return response.text().then(text => {

        const data = text && JSON.parse(text);
        var splittedToken
        var token
        var adminRights
        var userID
        if (authorizationHeader) {
            token = authorizationHeader
            splittedToken = authorizationHeader.split(" ")[1];
            adminRights = (JSON.parse(atob(splittedToken.split(".")[1]))).isAdministrator
            userID = (JSON.parse(atob(splittedToken.split(".")[1]))).userID;
        }

        if (!response.ok) {
            if (response.status === 401) {
                logout();
            }
            const error = (data && data.message) || response.statusText;
            return Promise.reject(error);
        } else {
            let userSession = {
                user: userID,
                accessToken: token,
                isAdmin: adminRights
            }
            return userSession
        }
    });
}

function logout() {
    console.error('Should logout')
}