/* global Backbone */
'use strict';

App.addInitializer(function(options){
    // http://stackoverflow.com/questions/19491336/get-url-parameter-jquery
    function getUrlParameter(sParam)
    {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++)
        {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam)
            {
                return sParameterName.length == 2 ? sParameterName[1] : "";
            }
        }
    };

    var screenshotParameterValue = getUrlParameter("screenshot");
    if (screenshotParameterValue === undefined) {
        return;
    }

    console.log("Running in screenshot mode: " + screenshotParameterValue);
    App.options.vegaRenderer = "canvas";
    window.devicePixelRatio = 2;


    //
    var $html = $("html");
    $html.addClass("screenshot");
    var screenshotTypes = _.invert(screenshotParameterValue.replace(/%7C/g, "|").split("|"));
    _.each(_.keys(screenshotTypes), function(screenshotType) {
        $html.addClass("screenshot_" + screenshotType);
        var wh = screenshotType.split("x");
        if (wh.length == 2) {
            var w = parseInt(wh[0]);
            var h = parseInt(wh[1]);
            if (w && h) {
                $("body").css({
                    "width": w,
                    "height": h,
                });
            }
        }
    });

    var intervalId = setInterval(function() {
        var ready = true;
//
//        var $vegas = $(".vega");
//        if (!$vegas.length) {
//            return;
//        }
//        $vegas.each(function() {
//            var $this = $(this);
//            var tagName = $this.children().eq(0).prop("tagName").toLowerCase();
//            if (tagName !== "svg" && tagName !== "canvas") {
//                ready = false;
//                return false;
//            }
//        });

        if (screenshotTypes["state_interface"]) {

        }

        if (ready) {
            if (screenshotTypes["state_interface"]) {
                //App.PlayerModule.$jPlayer.jPlayer("play", 42);
                //$(".player__slider-head_type_time").show();
                $(".player__slider-head_type_time")
                    .show()
                    .css("width", "100%");
                $(".player__time_type_before")
                .text("00:42");
                $(".player__time_type_after")
                .text("−01:59");

                //$(".player__slider-head_type_time").show();
            }

            if (screenshotTypes["state_flip"]) {
                var frame = 1;
                for (var i = 2; i < 7; i++) {
                    if (screenshotTypes["frame_" + i]) {
                        frame = i;
                    }
                }
                if (frame >= 2 && frame <= 5) {
                    App.context.get("state").set("musicRecordingsGridIsShown", true);
                    setTimeout(function() {
                        allDone();
                    }, frame * 50);
                }
                return;
            }

            allDone();
        }
    }, 5000);

    var allDone = function() {
        window.status = "screenshot_ready";
        console.log("screenshot is ready");
        clearInterval(intervalId);
    }

    //
    if (screenshotTypes["state_interface"]) {
        App.context.get("state").unserialize(JSON.parse('{"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"bl","composer":"Mozart","year":"","performer":"","title":"Symphony; 41","collection":"","place":""},"plannedParameterUpdates":{}},{"clientId":"cf544","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf562","parameters":{"library":"bl","title":"Symphony; 40","year":"","composer":"Mozart","performer":"","place":"","collection":""},"plannedParameterUpdates":{"year":"1970-1979","title":"Sonata"}},{"clientId":"cf170","parameters":{"library":"charm","title":"","year":"","composer":"Mozart","performer":"","recordingURI":"http://dml.org/charm/2378"},"plannedParameterUpdates":{}},{"clientId":"cf224","parameters":{},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom17","parameters":{"kind":"list","limit":"10","offset":"6","sortBy":"label"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tonic-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf780","parameters":{"kind":"key-relative-chord-seq","sequenceCount":"50","sequenceRepresentation":"parallel-coordinates","chordGrouppingIsByType":"1","guidesAreVisible":"1","recordingsInMajorModeAreIncluded":"1","recordingsInMinorModeAreIncluded":"1","chordTypesArePopularOnly":"","chordSequencesWithCyclesAreIncluded":"1","nIsIncluded":"","sequenceStepCount":"5"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf562","selectedViewConfigClientId":"cf780","entityWidth":260},"musicRecordingGrid":{"entityConfigs":[{"clientId":"cf204","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0181227XX-0200V0"},"plannedParameterUpdates":{}},{"clientId":"cf209","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163217XX-0100V0"},"plannedParameterUpdates":{}},{"clientId":"cf214","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1CL0046563XX-0100V0"},"plannedParameterUpdates":{}},{"clientId":"cf219","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163226XX-0100V0"},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"def4","parameters":{"kind":"properties"},"plannedParameterUpdates":{}},{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}}]}}'))
        App.play("http://dml.org/charm/2378");
        var $fakeMouse = $.bem.generateElement("screenshot", "fake-cursor");
        $fakeMouse.css({
            "left": 335,
            "top": 430,
        });
        $("body").append($fakeMouse);

        $fakeMouse.on("mouseover", function(event){
            console.log("here", arguments, $fakeMouse);
            event.pageX = 335;
            event.pageY = 430;
            App.TooltipModule.update(event, "C# → 15", $fakeMouse);

        });
        $fakeMouse.trigger("mouseover");

    }
    var teaserEntityWidth = 200;
    if (screenshotTypes["state_teaser"]) {
        //App.context.get("state").unserialize(JSON.parse('{"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"uganda","place":""},"plannedParameterUpdates":{}},{"clientId":"cf544","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf1681","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"dinka","place":""},"plannedParameterUpdates":{}},{"clientId":"cf660","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf602","parameters":{"kind":"pair","comparisonMode":"direct"},"plannedParameterUpdates":{}},{"clientId":"cf718","parameters":{"library":"bl","composer":"schoenberg","year":"","performer":"","title":"","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf480","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"symphony","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf418","parameters":{"library":"bl","title":"piano","year":"","composer":"","performer":"","place":"","collection":""},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom16","parameters":{"kind":"list"},"plannedParameterUpdates":{}},{"clientId":"custom17","parameters":{"kind":"pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"custom18","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tuning-stats","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf1872","parameters":{"kind":"mean-tempo-curve","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf780","parameters":{"kind":"pitch-class-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf481","parameters":{"kind":"tempo-histogram","tempoMin":"30","tempoMax":"300","tempoNumBins":"50","tempoPeriod":"1","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf1961","parameters":{"kind":"tonic-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf1647","selectedViewConfigClientId":"","entityWidth":' + teaserEntityWidth + '},"musicRecordingGrid":{"entityConfigs":[],"viewConfigs":[{"clientId":"def4","parameters":{"kind":"properties"},"plannedParameterUpdates":{}},{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}}]}}'))
        App.context.get("state").unserialize(JSON.parse('{"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"uganda","place":""},"plannedParameterUpdates":{}},{"clientId":"cf544","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf1681","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"dinka","place":""},"plannedParameterUpdates":{}},{"clientId":"cf660","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf602","parameters":{"kind":"pair","comparisonMode":"direct"},"plannedParameterUpdates":{}},{"clientId":"cf718","parameters":{"library":"bl","composer":"schoenberg","year":"","performer":"","title":"","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf480","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"symphony","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf418","parameters":{"library":"bl","title":"piano","year":"","composer":"","performer":"","place":"","collection":""},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom17","parameters":{"kind":"pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"custom18","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tuning-stats","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf780","parameters":{"kind":"pitch-class-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf481","parameters":{"kind":"tempo-histogram","tempoMin":"30","tempoMax":"300","tempoNumBins":"50","tempoPeriod":"1","widthToHeightRatio":"2"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf1647","entityWidth":200},"musicRecordingGrid":{"entityConfigs":[],"viewConfigs":[{"clientId":"def4","parameters":{"kind":"properties"},"plannedParameterUpdates":{}},{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}}]}}'))
    }
    if (screenshotTypes["state_teaser-wo-piano"]) {
        App.context.get("state").unserialize(JSON.parse('{"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"uganda","place":""},"plannedParameterUpdates":{}},{"clientId":"cf544","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf1681","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"","collection":"dinka","place":""},"plannedParameterUpdates":{}},{"clientId":"cf660","parameters":{"kind":"pair","comparisonMode":"superposition"},"plannedParameterUpdates":{}},{"clientId":"cf602","parameters":{"kind":"pair","comparisonMode":"direct"},"plannedParameterUpdates":{}},{"clientId":"cf718","parameters":{"library":"bl","composer":"schoenberg","year":"","performer":"","title":"","place":"","collection":""},"plannedParameterUpdates":{}},{"clientId":"cf480","parameters":{"library":"bl","composer":"","year":"","performer":"","title":"symphony","place":"","collection":""},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom16","parameters":{"kind":"list"},"plannedParameterUpdates":{}},{"clientId":"custom17","parameters":{"kind":"pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"custom18","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tuning-stats","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf1872","parameters":{"kind":"mean-tempo-curve","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf780","parameters":{"kind":"pitch-class-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf481","parameters":{"kind":"tempo-histogram","tempoMin":"30","tempoMax":"300","tempoNumBins":"50","tempoPeriod":"1","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf1961","parameters":{"kind":"tonic-histogram","widthToHeightRatio":"2"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf1647","selectedViewConfigClientId":"","entityWidth":' + teaserEntityWidth + '},"musicRecordingGrid":{"entityConfigs":[],"viewConfigs":[{"clientId":"def4","parameters":{"kind":"properties"},"plannedParameterUpdates":{}},{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}}]}}'));
    }

    if (screenshotTypes["state_flip"]) {
        var musicRecordingsGridIsShown = screenshotTypes["frame_6"] ? true : false;
        App.context.get("state").unserialize(JSON.parse('{"musicRecordingsGridIsShown":' + musicRecordingsGridIsShown + ',"musicCollectionGrid":{"entityConfigs":[{"clientId":"cf1647","parameters":{"library":"charm","composer":"Mozart","year":"","performer":"","title":""},"plannedParameterUpdates":{}},{"clientId":"cf562","parameters":{"library":"charm","title":"","year":"","composer":"Haydn","performer":""},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"custom17","parameters":{"kind":"list","limit":"10","offset":"6","sortBy":"label"},"plannedParameterUpdates":{}},{"clientId":"cf1783","parameters":{"kind":"tempo-histogram","widthToHeightRatio":"2","tempoMin":"30","tempoMax":"300","tempoNumBins":"50","tempoPeriod":"1"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf1647","selectedViewConfigClientId":"cf1783","entityWidth":260},"musicRecordingGrid":{"entityConfigs":[{"clientId":"cf209","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163217XX-0100V0"},"plannedParameterUpdates":{}},{"clientId":"cf471","parameters":{"kind":"pair","comparisonMode":"direct"},"plannedParameterUpdates":{}},{"clientId":"cf219","parameters":{"recordingURI":"http://sounds.bl.uk/resource/026M-1LP0163226XX-0100V0"},"plannedParameterUpdates":{}}],"viewConfigs":[{"clientId":"def5","parameters":{"kind":"midi-pitch-histogram"},"plannedParameterUpdates":{}},{"clientId":"cf397","parameters":{"kind":"tempo-nonuniform","widthToHeightRatio":"2"},"plannedParameterUpdates":{}},{"clientId":"cf494","parameters":{"kind":"tempo-normalised","widthToHeightRatio":"2"},"plannedParameterUpdates":{}}],"selectedEntityConfigClientId":"cf471","selectedViewConfigClientId":"cf494","entityWidth":220}}'));
    }



    var resizeIfNeededAfterADelay = function() {
        setInterval(function() {
            if (screenshotTypes["autosize_grid"] || screenshotTypes["autosize"]) {
                var $configGrid = $(".config-grid:visible");
                var $cellsSpace = $configGrid.find(".config-grid-cells__space");
                var maxX = 0;
                var maxY = 0;
                var $visInstances = $cellsSpace.find(".config-grid-cells__vis-instance");
                if (!$visInstances.length) {
                    resizeIfNeededAfterADelay();
                    return;
                }
                $visInstances.each(function() {
                    var $visInstance = $(this);
                    var position = $visInstance.position();
                    var currentMaxX = position.left + $visInstance.width();
                    var currentMaxY = position.top + $visInstance.height();
                    if (currentMaxX > maxX) {
                        maxX = currentMaxX;
                    }
                    if (currentMaxY > maxY) {
                        maxY = currentMaxY;
                    }
                });
                $cellsSpace.css({
                    "padding-right": 0,
                    "padding-bottom": 0,
                    "width": maxX,
                    "height": maxY,
                    "overflow": "visible"
                });



                if (screenshotTypes["autosize"]) {
                    var $body = $("body");
                    $body.width ($cellsSpace.offset().left + $cellsSpace.outerWidth());
                    $body.height($cellsSpace.offset().top  + $cellsSpace.outerHeight());
//                    var $html = $("html");
//                    $html.width ($cellsSpace.offset().left + $cellsSpace.outerWidth());
//                    $html.height($cellsSpace.offset().top  + $cellsSpace.outerHeight());
                }

                // console.log("VIEWPORT" + document.documentElement.clientWidth + " / " + document.documentElement.clientWidth);
                // console.log("BODY" + $body.width() + " / " + $body.height() );
            };
        }, 100);
    };
    resizeIfNeededAfterADelay();
    $(window).resize(resizeIfNeededAfterADelay);
});
