/* (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 WFS search.
 *
 *
 * To use the WFS search add the controller to the required classes
 * and to the conntrollers array in your app.
 *
    Ext.application({
        requires: [
            'LGB.ext4map.controller.Draw',
            ...
        ],
        controllers: [
            'Draw'
            ...
        ],
        ...
    });
 *
 * To search for WFS features in a WFS layer, set a valid configuration of
 * filters and resultsets in the layer configuration.
    {
        name: "WFS",
        url: "http://some/wfs/service",
        type: "wfs",
        options: {
            featureType: ['All'],
            version: '1.1.0',
            visibility: true,
            group: 'WFS',
        },
        search: {
            types: [{
                featureType: 'All',
                filter: ['name'],
                result: [{
                    display: 'firstname',
                    name: 'lastname'
                }, {
                    display: 'Firstname',
                    name: 'Lastname'
                }]
            }]
        }
    }
 */
Ext.define('LGB.ext4map.controller.WFSSearch', {
    extend: 'Ext.app.Controller',
    views: [
        'WFSSearch'
    ],
    refs: [{
        selector: 'wfssearch',
        ref: 'wfssearch'
    }],

    /**
     * @private
     * The store for search results.
     */
    store: null,

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

    /**
     * The layer to display result items on the map.
     */
    markerLayer: null,

    /**
     * @private
     * Initialize the controller.
     */
    init: function() {
        var me = this;
        this.highlightLayer = new ol.layer.Vector({
            source: new ol.source.Vector(),
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 153, 0, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: 'rgba(255, 0, 0, 1)'
                }),
                image: new ol.style.Icon({
                    src: window.bbviewerlib + 'img/markers/marker-gold.png'
                })
            }),
            name: 'WFSSearch',
            zIndex: 2012
        });
        this.control({
            'wfssearch textfield': {
                specialkey: me.search
            },
            'wfssearch button[action=search]': {
                click: me.searchBtn
            },
            'wfssearch button[action=reset]': {
                click: me.reset
            }
        });
    },

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

    /**
     * Search on hitting 'enter' in the search textfield.
     */
    search: function(field, evt) {
        if (evt.getKey() === 13) {
            var type = field.up('window').fType;
            this.find(field.getValue(), type);
        }
    },

    /**
     * Search on pressing search button.
     */
    searchBtn: function(btn) {
        var win = btn.up('window');
        var value = win.down('textfield[name=search]').getValue();
        var type = win.fType;
        this.find(value, type);
    },

    /**
     * Reset the search window and remove all markers from map.
     */
    reset: function(btn) {
        for (var i = 0; i < this.markerLayer.markers.length; i++) {
            this.markerLayer.removeMarker(this.markerLayer.markers[i]);
        }
        var win = btn.up('window');
        win.down('textfield[name=search]').setValue('');
        var store = win.store;
        store.removeAll();
    },

    /**
     * Execute the WFS search.
     */
    find: function(value, type) {
        var me = this;
        var tmp = this.getWfssearch();
        tmp.setLayer(this.markerLayer);
        var filterText = "<Filter><PropertyIsLike wildCard='*'" +
            " singleChar='#' escape='!'><PropertyName>" + type +
            "</PropertyName><Literal>" + value + "*</Literal></PropertyIsLike>" +
            "</Filter>";
        Ext.Ajax.request({
            url: this.application.appParams.app.searchUrl,
            method: 'GET',
            params: {
                'VERSION': '1.1.0',
                'SERVICE': 'WFS',
                'REQUEST': 'GetFeature',
                'TYPENAME': 'Alle',
                'maxFeatures': '100',
                'FILTER': filterText
            },
            callback: me.process,
            scope: me
        });
    },

    /**
     * Process the WFS response.
     */
    process: function(opts, success, response) {
        var store = this.getWfssearch().store;
        store.removeAll();

        var gml = new ol.format.GML();
        var features = gml.readFeatures(response.responseText);
        for (var i = 0; i < features.length; i++) {
            var feature = features[i];
            var item = {};
            for (var j = 0; j < store.model.getFields().length; j++) {
                item[store.model.getFields()[j].name] =
                    feature.attributes[store.model.getFields()[j].name];
            }
            item['geometry'] = feature.geometry;
            store.add(item);
        }
    }
});