import React, { useCallback, useEffect } from "react";
import JwtService from "@Front/Services/JwtService/JwtService";
import { IAppRule } from "@Front/Api/Entities/rule";
import { useRouter } from "next/router";
import Module from "@Front/Config/Module";

export enum RulesMode {
	OPTIONAL = "optional",
	NECESSARY = "necessary",
}

type IProps = {
	mode: RulesMode;
	rules: IAppRule[];
	children: JSX.Element;
	isPage?: boolean;
};

export default function Rules(props: IProps) {
	const router = useRouter();

	const [isShowing, setIsShowing] = React.useState(false);
	const [hasJwt, setHasJwt] = React.useState(false);

	const getShowValue = useCallback(() => {
		if (props.mode === RulesMode.NECESSARY) {
			return props.rules.every((rule) => JwtService.getInstance().hasRule(rule.name, rule.action));
		}
		return !!props.rules.find((rule) => JwtService.getInstance().hasRule(rule.name, rule.action));
	}, [props.mode, props.rules]);

	useEffect(() => {
		if (!JwtService.getInstance().decodeJwt()) return;
		setHasJwt(true);
		setIsShowing(getShowValue());
	}, [getShowValue, isShowing]);

	if (props.isPage && !isShowing) {
		router.push(Module.getInstance().get().modules.pages[404].props.path);
		return null;
	}

	if (!hasJwt || !isShowing) return null;

	return props.children;
}