angular.module('app').service('AppsZoomService', function ($rootScope, $localStorage, AppService, SQConstants, SQEvents) {

    function getCurrentZoom() {
        if ($storage.zoom) {
            $rootScope.zoom.current = Math.round($storage.zoom * 10) / 10;
            $rootScope.zoom.class = "zoom-" + String($rootScope.zoom.current).replace(".", "");
        }
        else if (SQConstants.getSettings().zoom) {
            var value = parseFloat(SQConstants.getSettings().zoom);
            $rootScope.zoom.current = Math.round(value * 10) / 10;
            $rootScope.zoom.class = "zoom-" + String($rootScope.zoom.current).replace(".", "");
            $storage.zoom = Math.round(value * 10) / 10;
        }

        window.sqAppZoom = $rootScope.zoom.current;
        resizeMiniResultPanels();
    }

    function resizeWindow() {
        setTimeout(function () {
            resizeMiniResultPanels();
            window.dispatchEvent(new Event('resize'));
        }, 50);
    }

    function resizeMiniResultPanels() {
        $(".dasboard-result-iframe").each(function (index) {
            var body = $(this).contents().find('body');
            body.css("zoom", $rootScope.zoom.current);
        });
    }

    this.changeZoom = function (value) {
        if (value >= $rootScope.zoom.min && value <= $rootScope.zoom.max) {
            AppService.saveSetting("zoom", value, function (result) {
                SQEvents.notifyListeners(SQEvents.get("ZOOM_CHANGED"), value);
                $storage.zoom = value;
                resizeWindow();
            });
        }
    }

    var instance = this;
    var $storage = $localStorage.$default();

    $rootScope.zoom = {
        current: 1,
        class: "zoom-1",
        min: 0.7,
        max: 1.8
    }

    getCurrentZoom();

    if (!isMainApp() && !isAlgoWizard() && window.top.addListener !== undefined) {
        window.top.addListener("AppsZoomService-" + window.appConfig.product, SQEvents.get("ZOOM_CHANGED"), function (event, data) {
            $rootScope.zoom.current = Math.round(data * 10) / 10;
            $rootScope.zoom.class = "zoom-" + String($rootScope.zoom.current).replace(".", "");
            window.sqAppZoom = $rootScope.zoom.current;
            $rootScope.$applyAsync();
            resizeWindow();
        });
    }

    if (isMainApp() && window.top.addListener !== undefined) {
        window.top.addListener("AppsZoomService-" + window.appConfig.product, SQEvents.get("ZOOM_CHANGED"), function (event, data) {
            var zoomNew = Math.round(data * 10) / 10;
            var awWindow = window.top.document.getElementById('algowizard-frame');
            if (awWindow) {
                awWindow = awWindow.contentWindow;
                if (awWindow && awWindow.eaWizardApp) {
                    awWindow.updateZoomAW(zoomNew);
                }
            }
        });
    }

});