import React from 'react';
import {createContext, useState, useEffect} from 'react';
import { Axios } from '../services/PhpApi';

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_width_cm: number,
  qr_height_cm: number,
  qr_fontsize: number,
  qr_visible_items: number,
  qr_item_sequence: number,
  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>>,
    getUser: () => Promise<void>,
    
    wait: boolean,
    setWait: React.Dispatch<React.SetStateAction<boolean>>,

    dog: ResponseT,
    setDog: React.Dispatch<any>
}

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

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

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


    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();
    },[]);
    
    return (
        <UserCtx.Provider value={
            {
                wait,
                setWait,
                user, 
                setUser, 
                getUser,
                dog,
                setDog
            }}
        >
            {children}
        </UserCtx.Provider>
    );

}