import * as React from 'react';
import {
    MmuiDefaultTable,
    MmuiDefaultTableProps,
    MmuiDefaultTableState,
} from './defaultTable';

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

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

export class MmuiDefaultTableSorted<
    P extends MmuiDefaultSortedTableProps,
    S extends MmuiDefaultSortedTableState
> extends MmuiDefaultTable<P, S> {
    constructor(props) {
        super(props);

        const order = {
            column: undefined,
            direction: undefined,
        };

        // @ts-ignore
        this.state.order = order;
        this.tableClassNameList.push('mmui-table-sortable');
    }

    handleSortOrderChange = (evt, col) => {
        evt.preventDefault();
        let orderDirection;
        if (this.state.order.column === col) {
            orderDirection =
                this.state.order.direction === 'ASC' ? 'DESC' : 'ASC';
        } else {
            orderDirection = 'ASC';
        }

        this.setState({
            order: {
                column: col,
                direction: orderDirection,
            },
        });

        this.props.updateTransform((t) => ({
            ...t,
            order: {
                column: col,
                method: orderDirection,
            },
        }));
    };

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

        let sortSymbol;
        if (this.state.order.direction == 'ASC') {
            sortSymbol = <i className="fas fa-caret-up"></i>;
        } else {
            sortSymbol = <i className="fas fa-caret-down"></i>;
        }
        return sortSymbol;
    }

    getColumnHeaderRender(colKey, index) {
        const records = this.props.records,
            classList: Array<string> = ['d-flex', 'flex-row'];

        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('justify-content-end');
                    }
                    break;
                }
            }
        }

        return (
            <th key={`table-head-${index}`}>
                <div className={classList.join(' ')}>
                    <a
                        href="#"
                        onClick={(e) => this.handleSortOrderChange(e, colKey)}
                    >
                        {this.props.columns[colKey]}
                    </a>
                    {this.getOrderDirection(colKey)}
                </div>
            </th>
        );
    }
}
