import { action, computed } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { emptyFunction, returnFalse, setupMoveUpEvents } from '../../../../../Utils';

interface TableBoxProps {
    pairs: { [key: string]: any }[];
    selectAxes: (axes: string[]) => void;
    axes: string[];
}

@observer
export class TableBox extends React.Component<TableBoxProps> {
    @computed get columns() {
        return this.props.pairs.length ? Array.from(Object.keys(this.props.pairs[0])) : [];
    }
    render() {
        return (
            <div className="table-container">
                <table className="table">
                    <thead>
                        <tr className="table-row">
                            {this.columns.map(col => (
                                <th
                                    style={{ color: this.props.axes.slice().reverse().lastElement() === col ? 'green' : this.props.axes.lastElement() === col ? 'red' : undefined, fontWeight: this.props.axes.includes(col) ? 'bolder' : 'normal' }}
                                    onPointerDown={e =>
                                        setupMoveUpEvents(
                                            {},
                                            e,
                                            returnFalse,
                                            emptyFunction,
                                            action(e => {
                                                const newAxes = this.props.axes;
                                                if (newAxes.includes(col)) {
                                                    newAxes.splice(newAxes.indexOf(col), 1);
                                                } else if (newAxes.length >= 1) {
                                                    newAxes[1] = col;
                                                } else {
                                                    newAxes[0] = col;
                                                }
                                                this.props.selectAxes(newAxes);
                                            })
                                        )
                                    }>
                                    {col}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {this.props.pairs?.map(p => {
                            return (
                                <tr className="table-row">
                                    {this.columns.map(col => (
                                        <td>{p[col]}</td>
                                    ))}
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>
        );
    }
}
