import React from 'react'
import Cookies from 'js-cookie'

export const AuthContext = React.createContext(null);

export function AuthProvider({ children }) {

    let [user, setUser] = React.useState(Cookies.get('token'));

    const context = {
        user,
        login: (token) => {
            try {
                Cookies.set('token', token, { expires: 7 })
                setUser(Cookies.get('token'))
            } catch (e) {
                console.log('Login Error >> ', e)
                Cookies.set('token', undefined)
            }
        },
        logout: () => {
            Cookies.set('token', undefined)
            setUser(undefined)
        },
        getToken: () => Cookies.get('token'),
        isLogged: () => {
            try {
                let CookiesUser = Cookies.get('token')
                if (!CookiesUser || CookiesUser === 'undefined') {
                    return false
                }
                // TODO:
                // add an method implmentation for 
                // check if cockie jwt is valid
                let logged = CookiesUser.length > 5
                console.log("is login? >>", logged)
                return logged

            } catch (e) {
                console.log("Error checking user ", e)
                return false
            }
        },
        setProfile: (obj) => Cookies.set('profile', JSON.stringify(obj)),
        getProfile: () => {
            let CookieProfile = Cookies.get('profile');
            if (CookieProfile) {
                return JSON.parse(CookieProfile);
            } else {
                return {}
            }
        },
        setRole: (role) => Cookies.set('role', JSON.stringify((role))),
        getRole: () => {
            let CookieRole = Cookies.get('role');
            if (CookieRole) {
                return JSON.parse(CookieRole);
            } else {
                return {}
            }
        }
    }

    return (
        <AuthContext.Provider value={context}>
            {children}
        </AuthContext.Provider>
    )
}


