import React from 'react';
import PropTypes from 'prop-types';

import {CommonListSorter, CommonListSorterProps} from './common/CommonListSorter';

export type PureListSorterProps = {
    currentSortingProperty: string;
    currentSortingDirection: string;
    onChangeSorting: Function;
} & CommonListSorterProps;

//CommonListSorter
export class PureListSorter<P extends PureListSorterProps> extends React.Component<P> {
    static propTypes = {
        currentSortingDirection: PropTypes.string.isRequired,
        onChangeSorting: PropTypes.func.isRequired,
        property: PropTypes.string.isRequired,
        currentSortingProperty: PropTypes.string.isRequired
    };

    handleChangeSorting = (property, direction) => {
        this.props.onChangeSorting(property, direction);
    };

    getDirection() {
        const {currentSortingProperty, currentSortingDirection, property} = this.props;

        if (currentSortingProperty !== property) {
            return null;
        }

        return currentSortingDirection;
    }

    render() {
        const {currentSortingProperty, currentSortingDirection, ...props} = this.props;

        return (
            <CommonListSorter
                {...props as any}
                onChangeSorting={this.handleChangeSorting}
                direction={this.getDirection()}
            />
        );
    }
}
