import React from 'react'
import PropTypes from 'prop-types'
import modalTypes from 'containers/modal-manager/modal-types'
import {Provider, withPortfolioNav} from './context'
import Controls from './partials/controls'
import Menu from './partials/menu'

class PortfolioNav extends React.PureComponent {
    static Controls = withPortfolioNav(Controls)
    static Menu = withPortfolioNav(Menu)

    state = {isOpen: false}

    get isControlled() {
        return typeof this.props.isOpen === 'boolean'
    }

    get isOpen() {
        return this.isControlled ? this.props.isOpen : this.state.isOpen
    }

    get childContext() {
        return {
            closeNav: this.closeNav,
            currentPorfolioId: this.props.currentPorfolioId,
            isOpen: this.isOpen,
            isSubscriptionActive: this.props.isSubscriptionActive,
            openNav: this.openNav,
            policy: this.props.policy,
            portfolios: this.props.portfolios,
            portfolioTimeseriesCollection: this.props
                .portfolioTimeseriesCollection,
            setPortfolio: this.props.setPortfolio,
            showPortfolioCreation: this.showPortfolioCreation,
            toggleNav: this.toggleNav,
        }
    }

    closeNav = (e) => {
        e && e.stopPropagation()

        if (!this.isControlled) {
            this.setState({isOpen: false})
        }

        this.props.onClose && this.props.onClose()
    }

    openNav = (e) => {
        e && e.stopPropagation()

        if (!this.isControlled) {
            this.setState({isOpen: true})
        }

        this.props.onOpen && this.props.onOpen()
    }

    toggleNav = (e) => {
        const isOpen = !this.isOpen
        const handler = isOpen ? this.openNav : this.closeNav

        handler(e)
    }

    showPortfolioCreation = () => {
        this.props.showModal &&
            this.props.showModal({type: modalTypes.MODAL_PORTFOLIO_CREATION})
    }

    render() {
        return (
            <Provider value={this.childContext}>{this.props.children}</Provider>
        )
    }
}

PortfolioNav.propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    currentPorfolioId: PropTypes.string,
    isOpen: PropTypes.bool,
    isSubscriptionActive: PropTypes.bool,
    policy: PropTypes.object,
    portfolioTimeseriesCollection: PropTypes.object,
    portfolios: PropTypes.object,
    setPortfolio: PropTypes.func,
    showModal: PropTypes.func,
    onClose: PropTypes.func,
    onOpen: PropTypes.func,
}

export default PortfolioNav
