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 DogT = 
{
  id: number,
  qr_id: string,
  email: string,
  name: string,
  phone: string,
  qr_code: string,
  picture: string
};

export type ResponseT = 
{
  success: number,
  status: number,
  message: string,
  fields: string,
  data: DogT
} | any;



export type UserCtxT =
{
    user: TUser | null,
    
    setUser: React.Dispatch<React.SetStateAction<TUser | null>>,
    
    registerUser: ({ email, password }: {
        email: string;
        password: string;
    }) => Promise<any>,
    
    updateDog: ({ email, name, phone }: {
        email: string;
        name: string;
        phone: 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,

    getDog: (str: string | undefined) => Promise<ResponseT>,

    dog: ResponseT
}

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/',
    baseURL: process.env.REACT_APP_PHP_ROOT,
});

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

    const [user, setUser] = useState<TUser | null>(null);
    const [wait, setWait] = useState(false);
    const [dog, setDog] = useState<ResponseT>({});

    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 updateDog = async ({email, name, phone}:
        {email: string, name: string, phone: string}) => {
        setWait(true);
        try{
            const {data} = await Axios.post('updateDog.php',{
                email,
                name,
                phone 
            });
            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 session =  await Axios.get('session.php');
            const {data} = session;
            if(data.success && data.user)
            {
                setUser(data.user);
                return;
            }
        }
        setUser(null);
    }

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

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

    const getDog = async ( str: string | undefined) =>
    {
      var ret: ResponseT = {};
      setWait(true);
    
      try 
      {
        ret = await Axios.post<ResponseT>('getDog.php', 
        {
          qr_id: str
        });
        setDog(ret.data as ResponseT);
        setWait(false);
        return;
      } 
      catch (error:any) 
      {
            console.log('error message: ', error.message);
            setWait(false);
            return;
      } 
    };
    
    return (
        <UserCtx.Provider value={
            {
                registerUser,
                updateDog,
                loginUser,
                wait, 
                user, 
                setUser, 
                getUser,
                logout,
                getDog,
                dog
            }}
        >
            {children}
        </UserCtx.Provider>
    );

}