/**
 * Render Heirarchy (for first Cell)
 *
 * @author Brauer Ilya
 * @date 2020-10-29
 */

import * as React from 'react';
import {ITreeNode, joinClassNames, safeInvoke} from '../../index';

import * as styles from './tree.m.scss';

interface IProps<T> {
    nodeChildren: Array<ITreeNode<T>> | null;
    level: number;
    isLast: boolean;
    expanded: boolean;
    onExpandClick?: () => void;
    node: ITreeNode<T>;
}

export class Hierarchy<T> extends React.PureComponent<IProps<T>> {

    get expandSymbol () {
        const {expanded, nodeChildren} = this.props;

        let content;

        if (nodeChildren) {
            content = expanded ? styles.open : styles.close;
        }

        return content;
    }

    handleExpandClick = (e: React.SyntheticEvent<HTMLDivElement>) => {
        e.stopPropagation();

        safeInvoke(this.props.onExpandClick);
    };

    override render () {
        const {level, node} = this.props;
        const levels = Array.from(new Array(level).keys());
        const isLastInLevel = Boolean(node.isLastInLevel);
        const isVLineInvisibleOnLvl: boolean[] = [];

        let tmpNode = node;

        for (let i = 0; i < level; i++) {
            isVLineInvisibleOnLvl.push(Boolean(tmpNode.isLastInLevel));

            if (tmpNode.parent) {
                tmpNode = tmpNode.parent;
            }
        }

        isVLineInvisibleOnLvl.reverse();

        return (
            <div className={styles.expandColumn}>
                {levels.map((i, index) => {
                    const vLineStyle = i < levels.length - 1 && isVLineInvisibleOnLvl[i] ?
                        styles.vDotLineInvisible : styles.vDotLine;

                    const className = joinClassNames(
                        vLineStyle,
                        [styles.vDotLineLast, isLastInLevel && index === levels.length - 1]
                    );

                    return (
                        <div
                            className={className}
                            key={i}
                        />
                    );
                })}

                <div className={styles.hDotLine}/>

                {this.expandSymbol && <div className={this.expandSymbol} onClick={this.handleExpandClick}/> }
            </div>
        );
    }
}
