"use strict";

App.module("GraphicsRenderingModule", function(GraphicsRenderingModule, App, Backbone, Marionette, $, _, Logger) {

    GraphicsRenderingModule.addInitializer(function(options){
        GraphicsRenderingModule.logger = Logger.get("GraphicsRenderingModule");


        GraphicsRenderingModule._formatNumberForTooltip = function(number) {
            var nDigits = 2;
            if (Math.abs(number) > 1000 || Math.floor(number) == number) {
                nDigits = 0;
            } else if (Math.abs(number) > 100) {
                nDigits = 1;
            }
            return _.str.numberFormat(number, nDigits);
        },

        GraphicsRenderingModule.__handleVegaMouseEvent = function() {

            var pointerEventType = arguments[0].type;

            if (pointerEventType == "mouseover" || pointerEventType == "mouseout") {
                var $vegaNode = $(arguments[0].target).closest("div");
                if (pointerEventType == "mouseover") {
                    $vegaNode.data("vegaHoveredItem", arguments[1]);
                } else {
                    $vegaNode.removeData("vegaHoveredItem");
                }
            }

            var data = null;
            if (arguments[1] && arguments[1].datum) {
                data = arguments[1].datum;
            }
            if (_.isObject(data) && data.tooltip) {
                // FIXME TMP HACK FOR GEOGRPAPHY
                App.TooltipModule.tooltipView.update(arguments[0], _.isArray(data.tooltip) ? data.tooltip[2] : data.tooltip, data);
            } else if (_.isArray(data)) {
                var tooltip = data[0];
                if (tooltip) {
                    var labelParts = [];

                    if (data[0] == "tooltip_range") {
                        labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[2]));
                        labelParts.push(" ... ");
                        labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[3]));
                        labelParts.push(" → ");
                        labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[1]).replace("-", "−"));
                    } else if (data[0] == "tooltip_point") {
                        if (data[2] * 1 === data[2]) {
                            labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[2]));
                        } else {
                            labelParts.push(data[2]);
                        }
                        labelParts.push(" → ");
                        labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[1]));
                    } else if (data[0] == "tooltip_value") {
                        labelParts.push(GraphicsRenderingModule._formatNumberForTooltip(data[1]).replace("-", "−"));
                    }

                    // prefix
                    if (data[4]) {
                        labelParts.unshift(data[4]);
                    }
                    // suffix
                    if (data[5]) {
                        labelParts.push(data[5]);
                    }

                    App.TooltipModule.tooltipView.update(arguments[0], labelParts.join(""), data);
                }
            } else {
                App.TooltipModule.tooltipView.update();
            }
        },

        /**
         * Draws a chart using vega, then executes callback when ready
//         */
//        GraphicsRenderingModule.vega = function ($domNode, spec, renderer, callback) {
//            var _this = this;
//            vg.parse.spec(spec, function(chart) { chart({
//                    el:$domNode.get(0),
//                    renderer: renderer ? renderer : "canvas",
//                    //hover: false
//                })
//                    .on('mouseover', GraphicsRenderingModule.__handleVegaMouseEvent)
//                    .on('mouseout', GraphicsRenderingModule.__handleVegaMouseEvent)
//                    .on('mousemove', GraphicsRenderingModule.__handleVegaMouseEvent)
//                    .update();
//            });
//            if (_.isFunction(callback)) {
//                var vegaIsReadyTimeout = setTimeout(function() {
//                    if (_this.vegaIsReady($domNode)) {
//                        callback($domNode);
//                        clearTimeout(vegaIsReadyTimeout);
//                    }
//                }, 50);
//            }
//        };
        GraphicsRenderingModule.vegaIsReady = function($domNode) {
            return $domNode.hasClass('vega');
        };

        GraphicsRenderingModule.vegaAsync = function ($domNode, spec, renderer, callback) {
            var rand = Math.random();
            $domNode.data("vega-async-rand", rand);
            var $tempNode = $("<div/>");
            setTimeout(function() {
                vg.parse.spec(spec, function(chart) {
                    var vegaObj = chart({
                        el:$tempNode.get(0),
                        renderer: App.options.vegaRenderer ? App.options.vegaRenderer : renderer,
                            //hover: false
                    })
                    .on('mouseover', GraphicsRenderingModule.__handleVegaMouseEvent)
                    .on('mousemove', GraphicsRenderingModule.__handleVegaMouseEvent)
                    .on('mouseout', GraphicsRenderingModule.__handleVegaMouseEvent)
                    .update();
                    var $vegaNode = $tempNode.children(0);
                    $vegaNode.data("vegaObj", vegaObj)

                    //console.log("VEGA DATA", vg, vegaObj._model._data);
                    var vegaIsReadyInterval = setInterval(function() {
                        if ($domNode.data("vega-async-rand") !== rand) {
                            clearInterval(vegaIsReadyInterval);
                            return;
                        }
                        if (GraphicsRenderingModule.vegaIsReady($vegaNode)) {
                            $vegaNode.addClass("vic-vega")
                            $domNode.empty().append($vegaNode);
                            clearInterval(vegaIsReadyInterval);
                        }
                    }, 50);
                });
            }, 10);
        };


    });
}, Logger);
