import * as React from "react";
import { observer } from "mobx-react";

import HTMLProps = React.HTMLProps;
import { BaseProps } from "@dewesoft-web/ui";
import * as theme from "./ContextMenu.scss";

import { ContextMenuModel } from "./ContextMenuModel";

export interface MenuProps extends HTMLProps<HTMLUListElement>, BaseProps {
    /** Provide your own model to expose the control settings to JS. */
    modelGrid : any;
    /** The unique name of the control */
    Name? : string;
}

@observer
export class ContextMenu extends React.Component<MenuProps, any> {

    model : ContextMenuModel;
    menu: any;
    id: string;

    constructor(props) {
        super(props);          
        
        this.id = this.props.modelGrid.name + "-menu";
        
        this.model = new ContextMenuModel(this.props.Name, this.props);
        this.model.onInitialized();    

        window.addEventListener("click",(event) => {
            Object.assign(this.menu.style, { 
                visibility: "hidden", 
                top: 0,
                left: 0 
            });
        }, false);

        this.editClick = this.editClick.bind(this);
        this.sortClick = this.sortClick.bind(this);
        this.unsortClick = this.unsortClick.bind(this);
    }

    editClick() {
        this.model.onClick();
    }

    sortClick() {
        this.props.modelGrid.sort(this.menu.dataset.column, true);
        this.model.onClick();
    }

    unsortClick() {
        this.props.modelGrid.unsort(true);
        this.model.onClick();
    }

    render() {
        return (
            <ul className={theme.contextMenu} id={ this.id } ref={e => this.menu = e}>
                <li onClick={this.editClick}>Edit columns</li>
                <li onClick={this.sortClick}>Sort by this column</li>
                <li onClick={this.unsortClick}>Unsort</li>
            </ul>
        );
    }
}
