import React, { useState, useEffect } from 'react';


export const NodeNavButton = (props) => {
    const {but, svc,setNextNode} = props;
    const [visible, setVisible] = useState(true);
    const [disabled, setDisabled] = useState(false);
    // VISIBLE   
    useEffect(() => {
        let sub;
        if (but.visible) {
            sub = but.visible(svc).subscribe(setVisible);
        } else {
            setVisible(true);
        }
        return () => {
            if (sub) {
                sub.unsubscribe();
            }
        };
    }, [but, svc]);
     // DISABLE   
     useEffect(() => {
        let sub;
        if (but.disable) {
            sub = but.disable(svc).subscribe(setDisabled);
        } else {
            setDisabled(false);
        }
        return () => {
            if (sub) {
                sub.unsubscribe();
            }
        };
    }, [but, svc]);
    const handleServerCall = (serverCalls, nextNode?) => {
        if (serverCalls) {
          Object.entries(serverCalls).forEach(([dataKey, call]: any) => {
            // store.dispatch(new MakeServerCall({ dataKey, ...call, nextNode }));
          });
        }
      };

    const showPortal = (portalData) => {
        const { type, paramFunc } = portalData;
        if (type === 'actionPanel') {
          //TODO: refactor this to -> callActionPanel() ...
          svc.navService.portalActions.next({ call: 'onClick', paramFunc });
        } else if (type === 'modal') {
          //
          svc.modalService.modalActions.next(paramFunc);
        }
      }
      
    return visible ?  (
        <props.buttonComponent 
            style={props.style}
            disabled={disabled}
            onClick={() => {
                //
                if (but.callback) {
                    but.callback(props);
                }
                //
                if (but.serverFirst) {
                    if (but.serverCalls && but.nextNode)
                    handleServerCall(but.serverCalls, but.nextNode);
                } else {
                    //
                    if (but.serverCalls) {
                        handleServerCall(but.serverCalls);
                    }
                    if (but.nextNode){
                        setNextNode(but.nextNode);
                    }
                }
                // SHOW PORTAL
                if (but.linkType && but.linkType === 'portal' && but.portalData) {
                    showPortal(but.portalData);
                }
            }}
            >
            {but.text}
         </props.buttonComponent>
    ) : null
};