/**
 * Boilerplate, which will be replaced with real content after load
 *
 * @author: Ilya Krenev
 * @date: 2022-05-25
 */

import * as React from 'react';
import * as styles from './Skeleton.m.scss';
import {joinClassNames} from '../../utils/joinClassNames';

type RowProps = {
    width?: string; // '10px' or '10%' or '10em'
    height?: string;
    margin?: string; // inline-style string
}

interface IProps {
    isLoading: boolean;
    isActive?: boolean;
    isRound?: boolean;
    isDark?: boolean;
    rows?: number;
    paragraph?: RowProps | boolean; // true by default
    title?: RowProps | boolean; // true by default
}

type DefaultProps = {
    isActive: boolean;
    isDark: boolean;
    paragraph: boolean;
    title: boolean;
    rows: number;
}

export class Skeleton extends React.Component<IProps> {
    static defaultProps: DefaultProps = {
        isActive: true,
        isDark: false,
        paragraph: true,
        title: true,
        rows: 5
    };

    renderSkeleton = () => {
        const {isActive, isRound, isDark, rows, paragraph, title} = this.props;

        let paragraphStyles: React.CSSProperties = {};
        let titleStyles: React.CSSProperties = {};

        if (typeof paragraph === 'object') {
            paragraphStyles = {
                margin: paragraph.margin,
                height: paragraph.height,
                width: paragraph.width
            };
        }

        if (typeof title === 'object') {
            titleStyles = {
                margin: title.margin,
                height: title.height,
                width: title.width
            };
        }

        return (
            <div
                className={joinClassNames(
                    styles.skeletonContainer,
                    [styles.active, Boolean(isActive)],
                    [styles.round, Boolean(isRound)],
                    [styles.dark, Boolean(isDark)],
                )}
            >
                {title && <div className={styles.skeletonTitle} style={titleStyles}/>}
                {paragraph &&
                (
                    <ul>
                        {[...Array(rows)].map((x, i) =>
                            (
                                <li key={i} className={styles.skeletonParagraph} style={paragraphStyles}/>
                            )
                        )}
                    </ul>
                )
                }
            </div>
        );
    }

    override render () {
        const isLoading = this.props.isLoading;

        if (isLoading) {
            return this.renderSkeleton();
        }

        return this.props.children || <React.Fragment/>;
    }
}
