import React from 'react';
import normalize from 'value-or-function';
import RadioExpand from '../radio-expand/radio-expand.jsx';
import RadioExpandItem from '../radio-expand/item.jsx';
import * as defaultMethodRenderers from './methods';

const propTypes = {
    enabled: React.PropTypes.oneOfType([
        React.PropTypes.bool,
        React.PropTypes.func
    ]),
    paymentApi: React.PropTypes.object.isRequired,
    methodRenderers: React.PropTypes.object
};

export default class PaymentContainer extends React.Component {

    static get defaultProps(){
        return {
            enabled: true,
            methodRenderers: defaultMethodRenderers
        };
    }

    constructor(props){
        super(props);
        this.renderedMethodDetails = {};
    }

    setData(id, data){
        const { paymentApi } = this.props;
        paymentApi.set(id, data);
    }

    onSelect(id){
        const selected = this.renderedMethodDetails[id];
        this.setData(id, selected.getData());
    }

    renderItem(method, index){
        const enabled = normalize.boolean(this.props.enabled, this);
        const { paymentApi } = this.props;
        const { selectedMethodId } = paymentApi.state;
        const { id, name, image, description } = method;
        const selected = id == selectedMethodId;
        const onSelect = this.onSelect.bind(this);
        return (
            <RadioExpandItem
                key={index}
                enabled={enabled}
                value={id}
                heading={name}
                image={image}
                description={description}
                selected={selected}
                onSelect={() => onSelect(id)}>
                {this.renderDynamicMethodDetails(id)}
            </RadioExpandItem>
        );
    }

    renderDynamicMethodDetails(id){
        const { methodRenderers } = this.props;
        const MethodDetails = methodRenderers[id];
        !MethodDetails && window.console.warn(`No renderer found for ${id}`);
        return MethodDetails ? this.renderMethodDetails(MethodDetails, id) : null;
    }

    renderMethodDetails(MethodDetails, id){
        const enabled = normalize.boolean(this.props.enabled, this);
        return (
            <MethodDetails
                enabled={enabled}
                setData={data => this.setData(id, data)}
                ref={child => this.renderedMethodDetails[id] = child} />
        );
    }

    render() {
        const { paymentApi } = this.props;
        const { methods } = paymentApi.state;
        const renderItem = this.renderItem.bind(this);
        return (
            <RadioExpand>
                {methods.map(renderItem)}
            </RadioExpand>
        );
    }
}

PaymentContainer.propTypes = propTypes;