import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { jsonParse, useReactorNavigation } from "../..";
/**
* Componente que renderiza un mati-button
* @name Reactor.Components.Input.MatiButton
* @param {string} clientid dato requerido por Mati
* @param {string} flowid dato requerido por Mati
* @param {string} color color del botón
* @param {string} metadata ver documentación de Mati
* @param {string} events Json string, cada propiedad del json es un tipo evento de Mati que se va a ejecutar como un ReactorLink al producirse un evento
* @param {string} href Operacion que se va a llamar en los eventos de Mati
* @param {string} main_style Estilos en formato html que se van a asignar al componente metamap-button-element
* @param {string} label Etiqueta del boton
* @class
* @example
<mati_button
clientid="123456789abcdefgh"
flowId="123456789abcdefgh"
color="#ff3f72"
main_style="border-radius:18px; height: 36px; font-size: 14px; font-weight: 600;"
label="VALIDÁ TU DNI"
metadata='{"user_id":"{{userId}}"}'
events='{
"userFinishedSdk": {"data": {"evento": "completo"}, "target": "navigate"},
"exitedSdk": {"data": {"evento": "saliosdk"}, "target": "navigate"}
}'
href="AppHomeVerificacion"
></mati_button>
*/
export const MatiButton = ({clientid, flowid, color, metadata, events, href, main_style, label = "Verificar DNI"}) => {
const ref = useRef();
const [loaded, setLoaded] = useState(false);
useEffect(()=>{
//console.log(ref.current.shadowRoot)
if(!loaded){
const timer = setInterval(()=>{
const figure = ref.current.shadowRoot.querySelector("metamap-button-element").shadowRoot.querySelector("figure");
if(figure){
const metamap = ref.current.shadowRoot.querySelector("metamap-button-element");
if(main_style)
metamap.setAttribute('style', main_style);
metamap.shadowRoot.querySelector("main").querySelector("label").innerHTML = label;
figure.setAttribute('style', 'display:none')
setLoaded(true);
}
}, 0);
return ()=>clearInterval(timer)
}
}, [loaded])
const objEvents = useMemo(() => {
return jsonParse({
json: events,
defaultValue: {},
onError: () => ({}),
})
}, [events]);
const navigation = useReactorNavigation({to: href});
const handler = useCallback((type) => {
if(objEvents[type]){
navigation.execute(objEvents[type].data, objEvents[type].target);
}
}, []);
const handleDivClick = () => {
handler("init");
}
useEffect(() => {
const currentRef = ref?.current;
if (currentRef) {
Object.keys(objEvents).forEach(type => {
currentRef.addEventListener(`mati:${type}`, ()=>handler(type), false);
})
}
return () => {
if (currentRef) {
Object.keys(objEvents).forEach(type => {
try{
currentRef.removeEventListener(`mati:${type}`);
}catch(e){}
})
}
};
}, [handler]);
return (
<div className={loaded ? "" : "d-none"} onClick={handleDivClick}>
<mati-button
ref={ref}
clientId={clientid}
flowId={flowid}
color={color}
metadata={metadata}
/>
</div>
);
}