/**
 *
 *
 * @author: Evgeniy Rusanov
 * @date: 2022-08-18
 */

import * as React from 'react';
import {joinClassNames, ColorScheme, safeInvoke, Skeleton} from '../../index';
import {ROW_HEIGHT} from './Node';

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

export interface ITreeContainerProps {
    isLoading: boolean;
    colorScheme?: ColorScheme;
    isStriped: boolean;
    onScroll?: (e: ScrollEvent) => void;
    isAutoHeightFill: boolean;
    nodesCount?: number;
    maxRowsBeforeOverflow?: number;
    additionalContent?: () => React.ReactNode | undefined;
}

export type ScrollEvent<T = Element> = React.SyntheticEvent<T> & {
    target: EventTarget & Partial<T>;
}

export class TreeContainer extends React.PureComponent<ITreeContainerProps> {
    private onScroll = (e: ScrollEvent): void => {
        safeInvoke(this.props.onScroll, e);
    }

    override render () {
        const {
            isLoading,
            colorScheme,
            isStriped,
            isAutoHeightFill,
            nodesCount,
            additionalContent,
            maxRowsBeforeOverflow = Infinity
        } = this.props;

        const containerClassName = joinClassNames(
            styles.treeContainer,
            colorScheme,
            [styles.isStriped, isStriped === true],
            [styles.hasAddButton, additionalContent !== undefined],
            [styles.isAutoHeightFill, isAutoHeightFill === true]
        );

        const style = isAutoHeightFill === true || nodesCount === undefined ? {} : {
            height: nodesCount < maxRowsBeforeOverflow ? 'auto' : `${ROW_HEIGHT * maxRowsBeforeOverflow}px`
        };

        return (
            <Skeleton isLoading={Boolean(isLoading)}>
                <div className={containerClassName} style={style} onScroll={this.onScroll}>
                    {this.props.children}
                </div>
                {additionalContent && additionalContent()}
            </Skeleton>
        );
    }
}
