import React from 'react';
import Card from '../card';
import CardNav from './card-nav.jsx';

/**\

    title: CardStack
    category: atom
    description: Allows navigation between leafs on a Card
    props:
        className[String]: Classes to be forwarded to the card
        onClose[Function]: A callback for when the stack is exited
        isOpen[Boolean]: Toggles the visibility of the Card

\**/
class CardStack extends React.Component {
    stack = [];
    state = {
        curr: 0
    };

    constructor(props) {
        super(props);

        this.stack = this.generateStack();
    }

    // to be overwritten by the subclass, returns an array of CardStackLeafs
    generateStack() {
        return [];
    }

    click() {
        if (this.state.curr > 0 && this.stack[this.state.curr].allowBack) {
            this.prev();
            return;
        }

        this.close();
    }

    close() {
        /* istanbul ignore else: no one cares */
        if (typeof this.props.onClose === 'function') {
            this.props.onClose();
        }

        setTimeout(() => {
            this.stack = this.generateStack();
            this.setState({
                curr: 0
            });
        }, 600);
    }

    next() {
        if (this.state.curr + 1 >= this.stack.length) {
            this.close();
            return;
        }

        this.setState({
            curr: ++this.state.curr
        });
    }

    prev() {
        if (this.state.curr === 0) {
            return;
        }

        this.setState({
            curr: --this.state.curr
        });
    }

    render() {
        const curr = this.stack[this.state.curr];
        let cancel = (
                <CardNav onClick={ this.click.bind(this) }/>
            ),
            form = false;

        if (curr) {
            form = React.createElement(
                curr.view,
                curr.getProps()
            );

            cancel = (
                <CardNav canBack={ this.state.curr > 0 && curr.allowBack }
                    onClick={ this.click.bind(this) }/>
            );
        }

        return (
            <Card className={ this.props.className }
                header={ this.header }
                left={ cancel }
                isOpen={ this.props.isOpen }>
                { form }
            </Card>
        );
    }
}

export default CardStack;
