/**
 * Created by Евгений Хохлов on 19.12.16.
 */
var frontView = (frontView) ? frontView : 0;
var bounds = new google.maps.LatLngBounds();
var lastPolygonCoordinate = (typeof polygons !== "undefined") ? polygons[polygons.length - 1][0][0] : null;
var goo = google.maps,
    map = new goo.Map(document.getElementById('map'), {
        center: (lastPolygonCoordinate) ? {lat: lastPolygonCoordinate[0], lng: lastPolygonCoordinate[1]} : {
            lat: -36.8581447,
            lng: 174.7593035
        },
        zoom: 12
    }),
    shapes = [],
    selected_shape = null,
    selected_shape_id = -1,
    byId = function (s) {
        return document.getElementById(s)
    },
    clearSelection = function () {
        if (selected_shape) {
            selected_shape.set((selected_shape.type
                ===
                google.maps.drawing.OverlayType.MARKER
            ) ? 'draggable' : 'editable', false);
            selected_shape = null;
            selected_shape_id = -1;
        }
    },
    setSelection = function (shape) {
        clearSelection();
        selected_shape = shape;
        selected_shape_id = shapes.indexOf(shape);
        selected_shape.set((selected_shape.type
            ===
            google.maps.drawing.OverlayType.MARKER
        ) ? 'draggable' : 'editable', true);

    },
    clearShapes = function () {
        for (var i = 0; i < shapes.length; ++i) {
            shapes[i].setMap(null);
        }
        shapes = [];
    },
    clearShape = function () {
        if (selected_shape_id > -1) {
            selected_shape.setMap(null);
            shapes.splice(selected_shape_id, 1);
        }
    };
if (!frontView) {
    var drawingManager = new google.maps.drawing.DrawingManager({
        drawingControl: true,
        drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_CENTER,
            drawingModes: [
                google.maps.drawing.OverlayType.POLYGON
            ]
        }
    });
    drawingManager.setMap(map);
    goo.event.addListener(drawingManager, 'overlaycomplete', function (e) {
        var shape = e.overlay;
        shapes.push(shape);
        goo.event.addListener(shape, 'click', function () {
            setSelection(this);
        });
        setSelection(shape);
    });

    goo.event.addListener(map, 'click', clearSelection);
    goo.event.addDomListener(byId('clear_shapes'), 'click', clearShapes);
    goo.event.addDomListener(byId('clear_shape'), 'click', clearShape);
    goo.event.addDomListener(byId('save_encoded'), 'click', function () {
        var data = IO.IN(shapes, false);


        //TODO: find why some shapes cant't be load from map.
        //find empty shapaes
        var emptyShapesArr = [];
        for (var oneShapeKey in data) {
            if (null === JSON.stringify(data[oneShapeKey]).match(/[0-9]/)) {
                emptyShapesArr.unshift(oneShapeKey);
            }
        }

        //skip empty shapes
        for (var i in emptyShapesArr) {
            data.splice(emptyShapesArr[i], 1);
            console.warn('skip shape #' + emptyShapesArr[i]);
        }

        data = JSON.stringify(data);

        $('#coveragemap-coverage').val(data);

    });

    var input = document.createElement('input');
    input.setAttribute('type', "file");
    input.setAttribute('name', "file");
    $(input).css({visibility: 'hidden'});
    $("body").append(input);

    goo.event.addDomListener(byId('load'), 'click', function () {

        $('[type=file][name=file]').remove();

        var input = document.createElement('input');
        input.setAttribute('type', "file");
        input.setAttribute('name', "file");
        $(input).css({visibility: 'hidden'});
        $("body").append(input);

        formdata = new FormData();

        $(input).change(function (evt) {
            if (typeof (this.files[0]) !== "undefined") {
                formdata.append("file", this.files[0]);
                $.ajax({
                    url: "/map/admin/convert-coverage-to-json",
                    type: "POST",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        if (data.length > 0) {
                            if (shapes) {
                                for (var i = 0; i < shapes.length; ++i) {
                                    shapes[i].setMap(null);
                                }
                            }
                            shapes = IO.OUT(data, map);
                            map.fitBounds(bounds);
                        } else {
                            alert('Wrong file format!');
                        }
                    }
                });
            }
        });

        input.click();
    });
}
var IO = {
    //returns array with storable google.maps.Overlay-definitions
    IN: function (arr,//array with google.maps.Overlays
                  encoded//boolean indicating whether pathes should be stored encoded
    ) {
        var shapes = [],
            goo = google.maps,
            shape;

        for (var i = 0; i < arr.length; i++) {
            shape = arr[i];
            shapes.push(this.m_(shape.getPaths(), encoded));
        }

        return shapes;
    },
    //returns array with google.maps.Overlays
    OUT: function (arr,//array containg the stored shape-definitions
                   map//map where to draw the shapes
    ) {
        var shapes = [],
            goo = google.maps,
            map = map || null,
            shape, tmp;

        for (var i = 0; i < arr.length; i++) {
            shape = arr[i];
            tmp = new goo.Polygon({paths: this.mm_(shape)});
            tmp.setValues({map: map})
            if (!frontView) {
                goo.event.addListener(tmp, 'click', function () {
                    setSelection(this);
                });
            } else {
                tmp.setOptions({strokeWeight: 3.0, fillColor: 'black', strokeColor: '#666'});

                if ("undefined" != typeof shapesCurrentOptions) {
                    tmp.setOptions(shapesCurrentOptions);
                }
            }
            shapes.push(tmp);
        }
        return shapes;
    },
    l_: function (path, e) {
        path = (path.getArray) ? path.getArray() : path;
        if (e) {
            return google.maps.geometry.encoding.encodePath(path);
        } else {
            var r = [];
            for (var i = 0; i < path.length; ++i) {
                r.push(this.p_(path[i]));
            }
            return r;
        }
    },
    ll_: function (path) {
        if (typeof path === 'string') {
            return google.maps.geometry.encoding.decodePath(path);
        }
        else {
            var r = [];
            for (var i = 0; i < path.length; ++i) {
                r.push(this.pp_.apply(this, path[i]));
                bounds.extend(this.pp_.apply(this, path[i]));
            }
            return r;
        }
    },

    m_: function (paths, e) {
        var r = [];
        paths = (paths.getArray) ? paths.getArray() : paths;
        for (var i = 0; i < paths.length; ++i) {
            r.push(this.l_(paths[i], e));
        }
        return r;
    },
    mm_: function (paths) {
        var r = [];
        for (var i = 0; i < paths.length; ++i) {
            r.push(this.ll_.call(this, paths[i]));

        }
        return r;
    },
    p_: function (latLng) {
        return ([latLng.lat(), latLng.lng()]);
    },
    pp_: function (lat, lng) {
        return new google.maps.LatLng(lat, lng);
    },
    b_: function (bounds) {
        return ([this.p_(bounds.getSouthWest()),
            this.p_(bounds.getNorthEast())]);
    },
    bb_: function (sw, ne) {
        return new google.maps.LatLngBounds(this.pp_.apply(this, sw),
            this.pp_.apply(this, ne));
    }

}

if (typeof polygons !== "undefined") {
    if (shapes) {
        for (var i = 0; i < shapes.length; ++i) {
            shapes[i].setMap(null);
        }
    }

    if (typeof coverages != "undefined") {
        shapes = [];
        coverages.forEach(function (el, index) {

            if (typeof coveragesConfig != "undefined") {
                shapesCurrentOptions = coveragesConfig[index];
            }

            shapes = shapes.concat(IO.OUT(el, map));
            delete shapesCurrentOptions;
        });

        map.addListener('tilesloaded', function () {
            map.fitBounds(bounds);
        });

    }
    else {
        shapes = IO.OUT(polygons, map);
        map.fitBounds(bounds);
    }

}

$('#coveragemap-submit').click(function (e) {
    e.preventDefault();

    $('#save_encoded').click();

    setTimeout(function () {
        $('#coveragemap-submit').submit();
    }, 200);

});