import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';

import {Column, ItemType} from './Column';

export class ColumnTreeView extends Component {
    static propTypes = {
        children: PropTypes.node,
        columns: PropTypes.arrayOf(
            PropTypes.shape({
                parentId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
                isActive: PropTypes.bool,
                selectedId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
                items: PropTypes.arrayOf(ItemType)
            })
        ),
        onSelect: PropTypes.func,
        countChildren: PropTypes.func,
        testAutomationId: PropTypes.string,
        fixedHeight: PropTypes.bool
    };

    static defaultProps = {
        children: null,
        columns: [],
        onSelect: id => {},
        countChildren: id => 0,
        testAutomationId: 'columnTreeView',
        fixedHeight: false
    };

    renderColumn = ({parentId, isActive, selectedId, items}, index) => {
        const {onSelect, countChildren} = this.props;

        return (
            <Column
                key={parentId}
                isActive={isActive}
                selectedId={selectedId}
                items={items}
                onSelect={onSelect}
                countChildren={countChildren}
                index={index}
            />
        );
    };

    renderChildren = () => {
        const {children} = this.props;
        let wrappedChildren = null;

        if (children) {
            wrappedChildren = <div className="rc-column-tree-view-content">{children}</div>;
        }

        return wrappedChildren;
    };

    render() {
        const {columns, testAutomationId, fixedHeight} = this.props;

        const classNames = classnames('rc-column-tree-view', {
            'rc-column-tree-view-fixed-height': fixedHeight
        });

        return (
            <div className={classNames} data-test-automation-id={testAutomationId}>
                {columns.map(this.renderColumn)}
                {this.renderChildren()}
            </div>
        );
    }
}
