import React from 'react';

class BathroomComponent extends React.Component
{
    constructor(props)
    {
        super(props);

        this.hostTable = React.createRef();
        this.headerLeft = React.createRef();
        this.headerCenter = React.createRef();
        this.headerRight = React.createRef();
        this.state = {doors:{}};
        this.settings = {};
    }
    componentDidMount()
    {
        this.getSettings();
        this.resizeTable();
    }
    async getSettings()
    {
        try
        {

            var url = window.location.origin + "/plugins/com.mattermost.bathroom/settings";
            var res = await fetch(url);
            this.settings = await res.json();
        }
        catch (e)
        {
            console.log(e);
            setTimeout(this.getSettings.bind(this), 5000);
            return;
        }

        Registry.registerWebSocketEventHandler("custom_com.mattermost.bathroom_updated", this.updateDoors.bind(this));
        this.updateDoors();
        this.interval = setInterval(this.updateDoors.bind(this), 90000);
    }
    componentWillUnmount()
    {
        if (this.interval)
        {
            clearInterval(this.interval);
            this.interval = null;
        }
        Registry.unregisterWebSocketEventHandler("custom_com.mattermost.bathroom_updated");
    }
    async updateDoors(msg)
    {
        //var url = Store.getState().entities.general.config.SiteURL + "/plugins/com.mattermost.bathroom/status";
        try
        {
            var url = window.location.origin + "/plugins/com.mattermost.bathroom/status";
            var res = await fetch(url);
            var json = await res.json();
            this.setState({"doors":json});
        }
        catch (e)
        {
            console.log(e);
            setTimeout(this.updateDoors.bind(this), 3000);
        }
    }
    render()
    {
        if (!this.state.doors) return;

        var borderString = "1px solid " + this.props.theme.sidebarText;

        var Host = props =>
            <div style={{"text-align": "center", width:"100%", "padding-top":"5px"}}>
            <table ref={this.hostTable} style={{"border-collapse":"collapse", "margin-left":"auto", "margin-right":"auto"}}>
            <tr>
              <td ref={this.headerLeft} style={{"border-bottom":borderString, "height":"11px"}}></td>
              <td ref={this.headerCenter}  rowspan={2} style={{"width":"22px", "text-align":"center"}}><img src={props.icon} style={{"width":"18px"}}/></td>
              <td ref={this.headerRight}  style={{"border-bottom":borderString}}></td>
            </tr>

            <tr>
              <td style={{"border-left":borderString}}></td>
              <td style={{"border-right":borderString}}></td>
            </tr>
            <tr>
              <td colspan={3} style={{"text-align":"center", "border-left":borderString,"border-right":borderString,"border-bottom":borderString}}>{props.content}</td>
            </tr>
            </table>
            </div>;

        var columns = 6;
        var keys = Object.keys(this.state.doors).sort();
        if (this.settings.door_order && this.settings.door_order.length == keys.length) keys = this.settings.door_order;
        var width = Math.floor(100 / (columns /*+ 1*/)) + "%";
        var widthPx = "23px";
        var elems = [];
        var row = [];
        var rows = 0;
        var IconImg = props => <img src={props.src} width="100%" style={{"padding":"2px"}} title={props.title}/>;
        var totalRows = Math.floor(keys.length / columns) + 1;
        for (var i = 0; i < keys.length /*(Math.floor(keys.length / 6) + 1) * 6*/; i++)
        {
            var img = null;
            if (i < keys.length)
            {
                var key = "" + keys[i];
                var door = this.state.doors[key];
                var imgs = this.settings[door + "_icons"];
                var index = parseInt(key) - 1;
                var imgFile = imgs[Math.max(0, Math.min(imgs.length - 1, index))];
                if (imgFile)
                {
                    img = <IconImg src={imgFile} title={this.settings.doors[key]}/>;
                    //img = <img src={imgFile} width="100%" style={{"padding":"2px"}} title={this.settings.doors[key]}/>
                }
            }
            row.push(<td width={widthPx}>{img}</td>);
            if (i % columns == columns - 1 || i == keys.length - 1)
            {
                /*
                if (rows == 0)
                {
                    row.unshift(
                        //<td rowspan={99} width={widthPx}><img src={this.settings.info_icon} width="100%" style={{"padding":"2px"}}/></td>
                        <td rowspan={totalRows} width={widthPx} style={{"color": this.props.theme.sidebarText, "padding-right":"5px"}}><IconImg src={this.settings.info_icon}/>:</td>
                    );
                }
                */
                elems.push(<tr style={{"height":"15px"}}>{[...row]}</tr>);
                row.length = 0;
                rows++;
            }
        }
        var content =
            <table style={{"margin":"5px", "margin-left":"auto", "margin-right":"auto"}}>
            {elems}
            </table>
        return <Host content={content} icon={this.settings.info_icon}/>;
    }
    componentDidUpdate()
    {
        this.resizeTable();
    }
    resizeTable()
    {
        this.headerLeft.current.width = this.headerRight.current.width = Math.max(50, (this.hostTable.current.clientWidth - this.headerCenter.current.clientWidth) / 2);
    }
}

var Registry = null;
var Store = null;

class BathroomMonitorPlugin
{
    initialize(registry, store)
    {
        Registry = registry;
        Store = store;
        registry.registerLeftSidebarHeaderComponent(BathroomComponent);
    }
}

window.registerPlugin('com.mattermost.bathroom', new BathroomMonitorPlugin());
