import * as React from "react";

import {
    MmuiDefaultSortedTableProps,
    MmuiDefaultSortedTableState,
    MmuiDefaultTableSorted,
} from "../../mmui-react-component";

export interface MmuiBlueDefaultTableSortedProps extends MmuiDefaultSortedTableProps {
    updateTransform: (t) => void;
}

export interface MmuiBlueDefaultTableSortedState extends MmuiDefaultSortedTableState {
    order?: any;
}

export class MmuiBlueDefaultTableSorted <
    P extends MmuiBlueDefaultTableSortedProps,
    S extends MmuiBlueDefaultTableSortedState
> extends MmuiDefaultTableSorted<P, S> {
    constructor(props) {
        super(props);

        this.tableClassNameList = ['mm-table'];
    }

    getOrderDirection(col) {
        if (col !== this.state.order.column) return null;

        let sortSymbol;
        if (this.state.order.direction == 'ASC') {
            sortSymbol = <button className="col-sort--asc" aria-label="Sort (ascending)"></button>;
        } else {
            sortSymbol = <button className="col-sort--des" aria-label="Sort (descending)"></button>;
        }
        return sortSymbol;
    }

    getColumnHeaderRender(colKey, index) {
        const records = this.props.records,
            classList: Array<string> = [],
            column = this.state.order.column;
        let aria = this.state.order.direction === 'ASC' ? 'ascending' : 'descending';

        if (colKey !== column) {
            aria = 'none'
        }

        if (records.length > 0) {
            let value;
            for (let i = 0; i < records.length; i++) {
                value = records[i][colKey];
                if (value !== undefined && value !== null) {
                    if (typeof value === 'number') {
                        classList.push('col--right');
                    }
                    break;
                }
            }
        }

        return (
            // @ts-ignore
            <th key={`table-head-${index}`}
                className={classList.join(' ')}
                aria-sort={aria}
                onClick={(e) => this.handleSortOrderChange(e, colKey)}>
                {this.props.columns[colKey]}
                {this.getOrderDirection(colKey)}
            </th>
        );
    }

}