import React from 'react';
import normalize from 'value-or-function';
import AddToCart from './add-to-cart.jsx';

const propTypes = {
    enabled: React.PropTypes.oneOfType([
        React.PropTypes.bool,
        React.PropTypes.func
    ]),
    showIcon: React.PropTypes.bool,
    text: React.PropTypes.string,
    showCounter: React.PropTypes.bool,
    itemId: React.PropTypes.string.isRequired,
    quantity: React.PropTypes.number,
    cartApi: React.PropTypes.object.isRequired
};

export default class AddToCartContainer extends React.Component {

    static get defaultProps(){
        return {
            enabled: true,
            showIcon: true,
            text: null,
            showCounter: false,
            quantity: 1,
            cartApi: {}
        };
    }

    count(){
        var items = this.props.cartApi.state.items;
        var id = this.props.itemId;
        var cartItem = items
            .filter(item => item.id == id)
            .pop();
        return cartItem ? cartItem.quantity : 0;
    }

    render() {
        const enabled = normalize.boolean(this.props.enabled, this);
        return (
            <AddToCart
                enabled={enabled}
                showIcon={this.props.showIcon}
                text={this.props.text}
                showCounter={this.props.showCounter}
                itemId={this.props.itemId}
                quantity={this.props.quantity}
                count={this.count()}
                onClick={this.props.cartApi.add}>
            </AddToCart>
        );
    }
}

AddToCartContainer.propTypes = propTypes;