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

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

export class ListSorter extends React.Component {
    static propTypes = {
        property: PropTypes.string,
        append: PropTypes.node,
        prepend: PropTypes.node
    };

    static defaultProps = {
        property: '',
        append: null,
        prepend: null
    };

    static contextTypes = {
        listStore: PropTypes.object
    };

    handleChangeSorting = (property, direction) => {
        this.context.listStore.sortBy(property, direction);
    };

    getDirection() {
        let sorting = this.context.listStore.getSorting();

        if (sorting.fieldId !== this.props.property) {
            return null;
        }

        return sorting.direction;
    }

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