import React, { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { uuid } from "../..";
import { IfContext } from "./If";
const objectPath = require("object-path");
/**
* Componente que usando el contexto if compara una variable con un valor y muestra un contenido condicionalmente
* @name Reactor.Components.Templates.IfCondition
* @param {string} path Cuando la variable es un objeto se puede establecer una ruta hacia el valor que se quiere tomar para comparar
* @param {string!} value Valor de la condicion
* @param {LogicOperator} [operator = "="] Operador para comparar el valor con la variable, por defecto es "="
* @param {VariableType?} type Tipo de variable que se va a comparar, por defecto es "text" (tomado del default del if)
* @class
* @example
<if variable="tipo" context="un_contexto">
<condition value="valor" operator="=" type="text">
contenido condicional
</condition>
<else>
contenido en caso contrario
</else>
</if>
*/
export const IfCondition = ({path = "", value, children, operator = "=", type}) => {
const [guid, setGuid] = useState(()=>uuid());
const {match, evalValue, addCondition, removeCondition, updateCondition} = useContext(IfContext);
const propValue = useMemo(()=>evalValue({type, value}), [value, type]);
useEffect(()=>{
addCondition({
guid,
value
});
return ()=>removeCondition({guid});
}, []);
useEffect(()=>{
updateCondition({
guid,
value: propValue,
operator,
path,
type
});
}, [propValue, operator, path, type]);
return (
<>
{match === guid ? children : <></>}
</>
)
}