const DEFAULT_CONFIG = 
{
    "numberofpages": 1,
    "orientation": "portrait",
    "pagedefinitions": [
        {
            "pagenumber": 0,
            "numberoffields": 1,
            "fielddefinitions": [
                {
                    "fieldnumber": 0,
                    "channelnumber": 65,
                    "fontcolour": "#ffffff",
                    "backgroundcolour": "#000000",
                    "headingcolour": "#ffffff",
                    "rules": []
                }
            ],
            "bordercolour": "#ffffff"
        }
    ],
    "lighting": [
        { "level": 0, "percent": 100 },
        { "level": 1, "percent": 15  },
        { "level": 2, "percent": 50  },
        { "level": 4, "percent": 80  }
    ],
    "splashscreen": {
        "enabled": false,
        "delay": 30000,
        "splashbackground": "#000000"
    },
    "rules": [],
    "button": "default",
    "largeheadings": false,
    "contextswitching": {
        "enable": false,
        "enprestart": false,
        "timerch": 117,
        "timetodisplaytimer": 5,
        "switchingvarch": 89,
        "minlimit": 60,
        "maxlimit": 135,
        "transition0to1": 1000,
        "transition1to0": 1000,
        "transition1to2": 1000,
        "transition2to1": 1000,
    }
};

function ParseConnectedDisplays(displays, milliseconds = 0) {

    let connected = [];

    for (let display in displays) {
        if (display.indexOf("bfd") >= 0 && displays.hasOwnProperty(display)) {
            var deviceInfo = displays[display];
            var splitStrings = deviceInfo.split(',')
            if (splitStrings.length == 3) {
                // Check display has been active in the last 1 minute
                if (milliseconds - parseInt(splitStrings[2]) < 60000) {
                    connected.push({device: display.toUpperCase(), instance: splitStrings[1], type: 'BFD', ipaddress: splitStrings[0]});
                    // connected.push(display.toUpperCase());
                }
            }
        } else if ((display.indexOf("qbd") >= 0) && displays.hasOwnProperty(display)) {
            const deviceInfo = displays[display];
            const splitStrings = deviceInfo.split(',')
            if (splitStrings.length == 3) {
                // Check display has been active in the last 1 minute
                if (milliseconds - parseInt(splitStrings[2]) < 60000) {
                    connected.push({device: display.toUpperCase(), instance: splitStrings[1], type: 'QBD', ipaddress: splitStrings[0]});
                    // connected.push(display.toUpperCase());
                }
            }
        }
    }

    return connected;
}

function ParseConfig(display, definitions) {
    let config = {};

    try {
        config = $.extend({}, DEFAULT_CONFIG, JSON.parse(definitions[display]));
    } catch (e) {
        config = DEFAULT_CONFIG;
    }

    return config;
}

//
// Class to syncronize a colour input element with a select element containing
// default colour values.
//
class ColourSync {

    constructor() {}

    addWidget(widget, defaultColour = "0xffffff") {
        widget.on('change', '.colour-select', this.onSelectChanged.bind(this));
        widget.on('change', '.colour-input', this.onInputChanged.bind(this));
        this.setColour(widget, defaultColour);
    }

    removeWidget(widget) {
        widget.off('change', '.colour-select', this.onSelectChanged.bind(this));
        widget.off('change', '.colour-input', this.onInputChanged.bind(this));
    }

    getColour(widget) {
        return widget.children('.colour-select').first().val();
    }

    setColour(widget, colour) {

        widget.children('.colour-input').val(colour);

        $.each(widget.children('.colour-select'), function(_idx, select) {
            if ($(select).children('option[value="' + colour + '"]').length > 0) {
                $(select).val(colour);
            }
            else {
                // Update Custom Option.
                $(select).children('.custom-value').val(colour);
                $(select).val(colour);
            }
        });
    }

    onSelectChanged(e) {
        let parent = $(e.target).parent('.colour-group');
        let $option = $(e.target).find(":selected");

        if ($option.hasClass('custom')){
            e.stopImmediatePropagation();
            $(e.target).siblings('input[type="color"]').first().click();
        }
        else {
            this.setColour(parent, $(e.target).val());
        }
    }

    onInputChanged(e) {
        let parent = $(e.target).parent('.colour-group');
        this.setColour(parent, $(e.target).val());
    }
}