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

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

import {SortDirection} from '../../../typings/common';

export const ASC = 'ASC';
export const DESC = 'ASC';
// export const KEY_ENTER: number;
// export const KEY_SPACE: number;

export interface ListSorterProps extends Partial<ListSorterDefaultProps> {
    children?: React.ReactNode;
    property?: string;
    displayName?: string;
    ascendingText?: string;
    descendingText?: string;
    sorterTitleText?: string;
}

export interface ListSorterDefaultProps {
    property: string;
    displayName: string;
    ascendingText: string | null;
    descendingText: string | null;
    sorterTitleText: string | null;
}

export type AccessibilityHeaderProps = {
    role: string;
    onKeyDown: typeof ListSorter.prototype.handleKeyDown;
    tabIndex: number;
    title: string;
};

// onClick(): void;
// getDirection(): ;
// renderSorterIcon(): React.Component<any>; // FIXME change it to Icon
// sorterClassName(): string;
// handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>): void;
// getAccessibilityHeaderProps(): AccessibilityHeaderProps;
// getAriaSortName(): string;

export class ListSorter extends React.Component<ListSorterProps> {
    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);
    };

    handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>): void {}

    getDirection(): SortDirection | null {
        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()}
            />
        );
    }
}
