/**
 * Component for displaying the number of records on a page as a tooltip
 *
 * @author: Ilya Brauer
 * @date: 2019-10-18
 */

import * as React from 'react';
import * as styles from './pageSize.m.css';
import {PLACEMENT, TRIGGER} from '../../../constants';
import {joinClassNames, Popover} from '../../../index';

interface IProps {
    value: string;
    rowsText: string;
    pageSizeOptions: number[];
    onChangePageSize: (size: number) => void;
    isDisabled?: boolean;
}

interface IState {
    visible: boolean;
}

export class PageSize extends React.Component<IProps, IState> {
    override state = {
        visible: false
    };

    private onChangePageSize = (size: number) => {
        return () => {
            this.props.onChangePageSize(size);
            this.toggleVisible(false);
        };
    };

    private toggleVisible = (visible: boolean) => {
        this.setState({visible});
    };

    override render () {
        if (this.props.isDisabled) {
            const classes = joinClassNames(
                styles.value,
                styles.isDisabled
            );

            return (
                <span className={classes} data-qaid={'pageSize'}>{this.props.value}</span>
            );
        }

        return (
            <Popover
                placement={PLACEMENT.TOP_END}
                trigger={TRIGGER.CLICK}
                isOpen={this.state.visible}
                onVisibleChange={this.toggleVisible}
                target={(<span className={styles.value} data-qaid={'pageSize'}>{this.props.value}</span>)}
            >
                <React.Fragment>
                    {this.props.pageSizeOptions.map((option, index) => {
                        return (
                            <div
                                key={`pageSize${index}`}
                                className={styles.sizeItem}
                                onClick={this.onChangePageSize(option)}
                                data-qaid={`pageSizeItem_${option}`}
                            >
                                {option} {this.props.rowsText}
                            </div>
                        );
                    })}
                </React.Fragment>
            </Popover>
        );
    }
}
