import * as React from "react";
import { observer } from "mobx-react";
import * as Highlighter from "react-highlight-words";

const ENTER = 13;
const ESC = 27;

import * as theme from "./StringCell.scss";

export const StringCell = observer(function StringCell({ cell, row, column, onValueChanged } : any) {

    const isEditing = row.selected && column.selected && cell.editing && !cell.isReadOnly;

    function renderView() {
        const valueType = typeof cell.data;

        let value : string;

        switch (valueType) {
            case "string":
                value = cell.data;
                break;
            default:
                if (cell.data || cell.data === 0) {
                    value = cell.data.toString();
                }
                value = "";
                break;
        }

        return (
            <div style={{ display: isEditing ? "none" : "" }}>
                <span>
                    <Highlighter searchWords={[cell.filter]}
                                 textToHighlight={value}
                    />
                    <span> {cell.suffix}</span>
                </span>
            </div>
        );
    }

    function editEnd(e) {
        if (onValueChanged && cell.dirty) {
            onValueChanged(cell.temp);
        }

        cell.editing = false;

        // console.log("BLUR!");
    }

    function changeValue(e) {
        cell.temp = e.target.value;
        cell.dirty = true;
    }

    function keyPress(e) {
        if (e.keyCode === ENTER) {
            cell.editing = false;
        }
        else if (e.keyCode === ESC) {
            cell.temp = cell.data;
            cell.editing = false;
        }
    }

    function renderEdit() {
        return (
            <input type="text"
                   value={cell.temp === null  ? "" : cell.temp} style={{ display: isEditing ? "" : "none" }}
                   onKeyUp={keyPress}
                   onChange={changeValue}
                   onBlur={editEnd}
            />
        );
    }

    const css = [
        (theme as any).typeString,
        isEditing ? (theme as any).editing : ""
    ].join(" ");

    return (
        <div className={css}>
            { renderView() }
            { renderEdit() }
        </div>
    );
});
