import React from "react";

class ButtonInteractive extends React.PureComponent {
    state = {
        pressed: 0,
        disabled: false,
    };

    timeoutid = false;

    componentWillUnmount() {
        if(this.timeoutid) {
            clearTimeout(this.timeoutid);
        }
    }

    onPress = (evt) => {
        const {step, onClick, resetTimeout} = this.props;
        const current = this.state.pressed;

        if(!step) {
            onClick(evt);

            this.setState({
                pressed: (current + 1)
            });
        } else {
            // when steps defined, zero is default comp and last is success comp, so subtract 2 from the length
            const qty = step.length - 2;

            if(current < qty) {
                this.setState({
                    pressed: (current + 1)
                });
                return;
            }
            if(current === qty) {
                // execute onclick evt on displaying last step
                onClick(evt);
                this.setState({
                    pressed: (current + 1),
                    disabled: true
                });

                // reset to default after x time, do nothing if clicked during it
                this.timeoutid = setTimeout(() => {
                    this.setState({
                        pressed: 0,
                        disabled: false
                    });
                }, ('undefined' !== typeof resetTimeout ? resetTimeout : 3000));
            }
        }
    };

    rendering = (props) => {
        let Comp = (props) => <button {...props}/>;
        if(this.props.comp) {
            Comp = this.props.comp;
        }
        return <Comp {...props}/>;
    };

    render() {
        const {step, children, className} = this.props;

        let style = {};
        if(this.props.style) {
            style = this.props.style;
        }
        if(this.state.disabled) {
            style.cursor = 'not-allowed';
        }

        return (
            <this.rendering className={className}
                            onClick={this.onPress}
                            disabled={this.state.disabled}
                            style={style}
            >{children ? children : null}{step && step[this.state.pressed] ? step[this.state.pressed] : null}</this.rendering>
        )
    }
}

export default ButtonInteractive;