import React from 'react'
import {createContext, useState, useEffect} from 'react'
import axios from 'axios'

export type TUserContextProviderProps =
{
    children: React.ReactNode
}

export type TUser =
{
    id: number,
    qr_id: string,
    email: string,
    name: string
}

export type UserCtxT =
{
    user: TUser | null,
    
    registerUser: ({ email, password }: {
        email: string;
        password: string;
    }) => Promise<any>,
    
    loginUser: (
        { email, password } : 
        {
        email: string;
        password: string;
        },
                ) => Promise<{
        success: number;
        message?: undefined;
    } | {
        success: number;
        message: any;
    }>,

    wait: boolean,

    getUser: () => Promise<void>,

    logout: () => void
}

export const UserCtx = createContext<UserCtxT | null>(null);

export const Axios = axios.create({
//    baseURL: 'http://localhost/dog/php-dog/',
    baseURL: 'https://hope-fly.de/dog/php-dog/',
});

export const UserCtxProvider = ({children}:TUserContextProviderProps) => {

    const [user, setUser] = useState<TUser | null>(null);
    const [wait, setWait] = useState(false);

    const registerUser = async ({email,password}:
        {email: string, password: string}) => {
        setWait(true);
        try{
            const {data} = await Axios.post('register.php',{
                email,
                password 
            });
            setWait(false);
            return data;
        }
        catch(err){
            setWait(false);
            return {success:0, message:'Server Error!'};
        }
    }

    const loginUser = async ({email,password}:{email: string, password: string}) => 
    {
        setWait(true);
        try
        {
            var postReturn:
            {   
                data:
                {
                    success: number;
                    message: string;
                    data: TUser | null;
                } 
            } 
            = { data : {success: 0, message: '', data: null } };




            postReturn = await Axios.post('login.php',{
                    email,
                    password 
                });

            const {data} = postReturn;
            if(data.success && data.data)
            {
                setUser(data.data);
                setWait(false);
                return {success:1};
            }
            setWait(false);
            return {success:0, message:data.message};
        }
        catch(err){
            setWait(false);
            return {success:0, message:'Server Error!'};
        }

    }

    const getUser = async () => 
    {
        if(user)
        {
            const {data} = await Axios.get('getUser.php');
            if(data.success && data.user)
            {
                setUser(data.user);
                return;
            }
            setUser(null);
        }
        else
        {
            const {data} = await Axios.get('session.php');
            if(data.success && data.user)
            {
                setUser(data.user);
                return;
            }
        }
    }

    useEffect(() => 
    {
        async function asyncCall()
        {
            await getUser();
        }
        asyncCall();
    },[]);

    const logout = async () => 
    {
        await Axios.get('logout.php');
        setUser(null);
    }

    return (
        <UserCtx.Provider value={
            {
                registerUser,
                loginUser,
                wait, 
                user, 
                getUser,
                logout
            }}
        >
            {children}
        </UserCtx.Provider>
    );

}