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 "./NumberCell.scss";

function getFormattedData(value, decimals) : string {
    let data = value == null ? "" : value;
	
    if (typeof data !== "number") {
		data = parseFloat(data);
    }	
	
    if (decimals !== null && decimals !== undefined) {
        return isNaN(data) ? "" : data.toFixed(decimals);
    }
    return data.toString();
}

export const NumberCell = observer(function NumberCell({ cell, row, column, onValueChanged } : any) {

    const isEditing = row.selected && column.selected && cell.editing && !cell.isReadOnly;

    function renderView() {
        const { decimals, suffix, ...typeOptions } = cell.type;

        const data = getFormattedData(cell.data, decimals);

        return (
            <div style={{ display: isEditing ? "none" : "" }}>
                <span>
                    <Highlighter searchWords={[cell.filter]}
                                 textToHighlight={data || ""}
                    />
                    <span> {suffix}</span>
                </span>
        </div>
        );
    }

    function editEnd(e) {
        if (onValueChanged && cell.dirty) {
            const value = parseFloat(cell.temp);
            onValueChanged(value);
        }

        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() {
        const { decimals, suffix, kind, ...typeOptions } = cell.type;

        const data = cell.temp == null ? "" : cell.temp;

        return (
            <input type="number"
                   defaultValue={data} style={{ display: isEditing ? "" : "none" }}
                   step="any"
                   {...typeOptions}
                   onKeyUp={keyPress}
                   onChange={changeValue}
                   onBlur={editEnd}
            />
        );
    }

    const css = [
        (theme as any).typeNumber,
        isEditing ? (theme as any).editing : ""
    ].join(" ");

    return (
        <div className={css}>
            { renderView() }
            { renderEdit() }
        </div>
    );
});

