import * as React from "react";
import { observer } from "mobx-react";
import { getOptions } from "../../util"
import * as Highlighter from "react-highlight-words";

import * as theme from "./EnumCell.scss";

const ENTER = 13;

function getDescription(cell) : string {
    if (!cell.type || !cell.type.options) {
        return cell.data;
    }

    for (const opt of cell.type.options) {
        if (opt.value === cell.data) {
            return opt.description;
        }
    }

    return cell.data;
}

export const EnumCell = observer(function EnumCell({ cell, row, column, onValueChanged, onStartEdit } : any) {

    const selected = row.selected && column.selected;
    const isEditing = selected && cell.editing;

    function renderView() {
        let description : any = getDescription(cell);
        if (typeof description !== "string") {
            if (!description && description !== 0) {
                description = "";
            }
            else {
                description = description.toString();
            }
        }

        return [
            <div key="view" className="view">
                <Highlighter searchWords={[cell.filter]}
                             textToHighlight={description}
                />
            </div>,
            <i key="icon" className="material-icons enum-icon">arrow_drop_down</i>
        ];
    }

    function onChange(e) {
        if (isEditing && onValueChanged) {
            onValueChanged(e.target.value);
        }
    }

    function renderEdit() {
        return (
            <select onChange={onChange} value={cell.data}>
                {
                    getOptions(cell).map(function(opt) {
                        return (
                            <option value={opt.value}
                                    key={opt.value}>
                                {opt.description}
                            </option>);
                    })
                }
            </select>
        );
    }

    function onKeyDown(e) {
        switch (e.keyCode) {
            case ENTER:
                if (!isEditing) {
                    onStartEdit(cell);
                }
                break;
            default:
                break;
        }
    }

    const css = [
        (theme as any).typeEnum,
        isEditing && !cell.isReadOnly ? (theme as any).editing : null,
        selected ? (theme as any).selected : null
    ].join(" ")
     .trim();

    return (
        <div className={css} tabIndex={999} onKeyDown={onKeyDown}>
            { renderView() }
            { renderEdit() }
        </div>
    );
});
