/* (C) GeoBasis-DE/LGB
 * Copyright by Landesvermessung und Geobasisinformation Brandenburg (LGB)
 *
 * Software engineering by Intevation GmbH
 *
 * This file is Free Software under the GNU GPL (>=v3)
 * and comes with ABSOLUTELY NO WARRANTY! Check out the
 * LICENSE for details.
 */

/**
 * Controller for the print module.
 *
 * To use the print module add the controller to the controllers array in
 * your app and activate the tool in the
 * {@link LGB.ext4map.view.Toolbar toolbar}.
 *
    Ext.application({
        classicControllers: [
            'Print',
            ...
        ],
        ...
    });
 *
 * To set the print URL call {@link LGB.ext4map.controller.Print#setPrintUrl}.
 * To set non printable layers call
 * {@link LGB.ext4map.controller.Print#setBlacklist} with an array of layers.
 */
Ext.define('LGB.ext4map.controller.Print', {
    extend: 'Ext.app.Controller',
    requires: ['LGB.ext4map.view.PrintInfo'],
    alias: 'controller.print',

    /**
     * The OpenLayers map object.
     */
    map: null,

    /**
     * @private
     * The capabilities document of the print service.
     */
    capabilities: null,

    /**
     * The layer blacklist.
     * Layers in this list are excluded from printing.
     */
    blacklist: [],

    /**
     * @private
     * The print info view.
     */
    info: null,

    /**
     * @private
     * Initialize the controller and map the events.
     */
    init: function() {
        var me = this;
        this.control({
            'print button[action=accepted]': {
                click: me.showPrintInfo
            },
            'printinfo button[action=bbox]': {
                click: me.print
            }
        });
    },

    /**
     * Set the OpenLayers map object.
     */
    setMap: function(map) {
        this.map = map.map;
    },

    /**
     * Set the URL to the print service.
     */
    setPrintUrl: function(url) {
        this.capabilities = Ext.create('LGB.ext4map.util.PrintCapabilities', {
            url: url + 'info.json'
        });
    },

    /**
     * Set the layer blacklist.
     */
    setBlacklist: function(list) {
        this.blacklist = list;
    },

    /**
     * Show the print info dialog.
     */
    showPrintInfo: function() {
        this.info = Ext.widget('printinfo');
        this.info.show();
    },

    /**
     * Print the current map configuration.
     */
    print: function() {
        var bounds = this.map.getView().calculateExtent(this.map.getSize());
        leftbottomX = bounds[0];
        leftbottomY = bounds[1];
        righttopX   = bounds[2];
        righttopY   = bounds[3];

        var dt = Ext.Date.format(new Date(),'d.m.Y');

        var toolbox = Ext.create('LGB.ext4map.util.Toolbox');
        var scale = toolbox.getScaleFromResolution(
            this.map.getView().getResolution());

        //visible layer for printing
        dienste = '';
        var layers = this.map.getLayers().getArray();
        var printLayers = [];
        for(i = 0 ; i < layers.length; i++) {
            var layer = layers[i];
            if (this.blacklisted(layer)) {
                continue;
            }
            // continue when layer is activated only
            if(!layer.getVisible() ||
               !(layer instanceof ol.layer.Image)) {
                continue;
            }
            else {
                var name = layer.get('name');
                dienste += name;
                printLayers.push(layer);
            }
        }
        var dpis = this.capabilities.getDpis();
        var layouts = this.capabilities.getLayouts();
        var scales = this.capabilities.getScales();
        var createUrl = this.capabilities.createUrl;
        var options = {
            createUrl: createUrl,
            method: 'POST',
            layers: printLayers,
            services: dienste,
            dpi: dpis.getAt(0).get('value'),
            layout: layouts.getAt(0).get('name'),
            scale: this.capabilities.getScale(
                toolbox.getScaleFromResolution(
                    this.map.getView().getResolution(),
                    this.map.getView().getProjection().getUnits())),
            map: this.map
        };
        this.printer = Ext.create('LGB.ext4map.util.Print', options);
        this.printer.print();
        this.info.hide();
    },

    /**
     * Check if a layer is on the blacklist.
     */
    blacklisted: function(layer) {
        for (var i = 0; i < this.blacklist.length; i++) {
            if (this.blacklist[i].id === layer.id) {
                return true;
            }
        }
        return false;
    }
});