import React, { useState, useMemo, ReactNode } from "react";
import { endpoints } from "../../utils/api";
import { PermissionsDto } from "types/dtos";
import { useSWR, fetcher } from "units/swr";
import { blip } from "utils";

type UserPermissionsContextPayload = {
  permissions: string[];
  loading: boolean;
};

const initialState: UserPermissionsContextPayload = {
  permissions: [],
  loading: true
};

const UserPermissionsContext = React.createContext<UserPermissionsContextPayload>(initialState);

type Props = {
  children: ReactNode;
};

const UserPermissionsProvider: React.FC<Props> = ({ children }) => {
  const [state, setState] = useState<UserPermissionsContextPayload>(initialState);

  const url = useMemo(() => (state.permissions?.length ? null : endpoints.security.permissions), [state.permissions]);
  useSWR<PermissionsDto, Error>(url, fetcher, {
    revalidateOnFocus: false,
    onError: err => blip.error(err.message),
    onSuccess: data => setState({ ...data, loading: false })
  });

  return <UserPermissionsContext.Provider value={state}>{children}</UserPermissionsContext.Provider>;
};

export { UserPermissionsProvider, UserPermissionsContext };
export default UserPermissionsProvider;
