/**
 * WebIQ Visuals widget template.
 * @version 1.2
 */
(function () {
    'use strict';

    // variables for reference in widget definition
    const className = "CxChart", // widget name in camel case
        uiType = "cx-chart", // widget keyword (data-ui)
        isContainer = false;

    // example - default configuration
    const defaultConfig = {
        "class-name": "cx-chart",
        "name": null,
        "template": "custom/controls/cx-chart"
    };

    // setup module-logger
    const ENABLE_LOGGING = true, //enable logging with 'log' function
        RECORD_LOG = false, //store logged messages in logger memory
        logger = shmi.requires("visuals.tools.logging").createLogger(uiType, ENABLE_LOGGING, RECORD_LOG),
        fLog = logger.fLog, //force log - logs message even if logger is disabled
        log = logger.log; //log message if logger is enabled
    let jX = {}
    let jY = {}

    // declare private functions - START

    // declare private functions - END

    // definition of new widget extending BaseControl - START
    const definition = {
        className: className,
        uiType: uiType,
        isContainer: isContainer,
        /* default configuration settings - all available options have to be initialized! */
        config: defaultConfig,
        /* instance variables */
        vars: {
            //references for DOM elements accessed with JS code
            elements: {
                divPlotly: null       //div for trendly output
            },
            itemType: null,
            itemX: null,
            itemY: null,
            // data of plotly chart
            plotlyGraph: null,
            plotlyData: null,
            plotlyLayout: null,
            plotlyConfig: null,
        },
        /* imports added at runtime */
        imports: {
            /* example - add import via shmi.requires(...) */
            im: "visuals.session.ItemManager",
            io: "visuals.io"
        },

        /* array of custom event types fired by this widget */
        events: [],

        /* functions to extend or override the BaseControl prototype */
        prototypeExtensions: {
            /* called when config-file (optional) is loaded and template (optional) is inserted into base element */
            onInit: function () {
                const self = this
                const { elements } = self.vars;
                elements.divPlotly = shmi.getUiElement("plotly", self.element)
            },
            /* called when widget is enabled */
            onEnable: function () {
                const self = this
                const { im } = self.imports
                // Subscribe to item updates
                if (self.config.itemX && self.config.itemY) {
                    self.vars.itemX = im.subscribeItem(self.config.itemX, self)
                    self.vars.itemY = im.subscribeItem(self.config.itemY, self)
                }
            },
            /* called when widget is disabled */
            onDisable: function () {

            },
            /* called when widget is locked - disable mouse- and touch-listeners */
            onLock: function () {

            },
            /* called when widget is unlocked - enable mouse- and touch-listeners */
            onUnlock: function () {

            },
            /* called by ItemManager when value of subscribed item changes and once on initial subscription */
            onSetValue: async function (value, type, name) {
                const self = this
                let elems = self.vars.elements
                let vars = self.vars

                if (value === "") {
                    value = "{}"
                }
                try {
                    if (name === self.config.itemX) {
                        jX = JSON.parse(value)
                    } else if (name === self.config.itemY) {
                        jY = JSON.parse(value)
                    }
                } catch (e) {
                    shmi.notify(name + ": " + e.message)
                }
                if (self.config.itemType === "pie") {
                    vars.plotlyData = [
                        { type: "pie", labels: jX, values: jY }
                    ]
                } else if (self.config.itemType === "bar") {
                    vars.plotlyData = [
                        { x: jX, y: jY, type: "bar" }
                    ]
                } else {
                    vars.plotlyData = [
                        { x: jX, y: jY, type: "line" }
                    ]
                }
                vars.plotlyLayout = {
                    title: shmi.localize(self.config.chartTitle),
                    yaxis: {
                        zeroline: false
                    },
                    xaxis: {
                        tickangle: -30
                    }
                }
                vars.plotlyConfig = {
                    scrollZoom: false,
                    responsive: true,
                    // double click delay for reset zoom
                    doubleClickDelay: 500,
                    // true: display always false: hide
                    displayModeBar: false
                }
                if (jX && jY) {
                    vars.plotlyGraph = await Plotly.newPlot(elems.divPlotly, vars.plotlyData, vars.plotlyLayout, vars.plotlyConfig)
                }
            },
            /* called by ItemManager to provide properties (min & max values etc.) of subscribed item */
            onSetProperties: function (min, max, step, name, type, warnMin, warnMax, prewarnMin, prewarnMax, digits) {

            },
            /* called when widget is deleted - used for instance clean-up */
            onDelete: function () {
                const self = this
                log("onDelete " + self.config.itemOsziMsg)
                Plotly.purge(self.vars.elements.divPlotly);

                jX = {}
                jY = {}
                self.vars.elements.trendlyGraph = {}
                self.vars.elements.trendlyData = {}
                self.vars.elements.trendlyLayout = {}
                self.vars.elements.trendlyConfig = {}
            }
        }
    };

    // definition of new widget extending BaseControl - END

    // generate widget constructor & prototype using the control-generator tool
    shmi.requires("visuals.tools.control-generator").generate(definition);
})();
