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

export const AuthContext = React.createContext();

export function AuthProvider ({ children }){

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

    const context = {
        user,
        login: (user) => {

            try{
                let body = JSON.stringify( user )
                Cookies.set('user', body, { expires : 7 })
                setUser(Cookies.get('user'))
            }catch(e){
                console.log('Error >> ', e)
                Cookies.set('user', undefined)
            }

        },
        logout : () => {
            Cookies.set('user', undefined)
            setUser(undefined)
        },
        isLogged : () => {
            let CookiesUser = Cookies.get('user')
            console.log('existe usuario -> ', CookiesUser)
            if(!CookiesUser || CookiesUser === 'undefined'){
                return false
            }
            return !!CookiesUser
        }
    }

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


