import React from "react";
import { User } from "../types";

export interface IUserContextType {
  user: User | undefined;
  updateUser: (u: User) => void;
  getUser: () => User | undefined;
}

const defaultValue: IUserContextType = {
  user: undefined as User | undefined,
  updateUser: () => ({}),
  getUser: () => undefined,
};

export const UserContext = React.createContext<IUserContextType>(
  defaultValue as IUserContextType,
);

const UserProvider: React.FC<React.ReactNode> = ({ children }) => {
  const [user, setUser] = React.useState<User>(undefined as any);

  return (
    <UserContext.Provider
      value={{
        user,
        updateUser: (user: User) => setUser(user),
        getUser: () => user,
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

export default UserProvider;
