/* global Bdf,$$,Geo */

Geo.Geocodage = {};

Geo.Geocodage.ARGS = {
    clientId: "",
    latitudeId: "",
    longitueId: "",
    addressArray: [],
    start: null
};

Geo.Geocodage.init = function (args) {
    var geoId = Bdf.generateId();
    var geoPosition;
    var withAdressSource = (args.addressArray.length > 0);
    $$(args.clientId).html(Bdf.render("geo:geocodage", {
        geoId: geoId,
        withAdressSource: withAdressSource
    }));
    _$$("cancel").click(function () {
        window.close();
    });
    _$$("confirm").click(_validation);
    _$$("center", "current").click(function () {
        geoPosition.centerOn(Geo.Position.CURRENT_POSITION_KEY);
    });
    _$$("center", "new").click(function () {
        geoPosition.centerOn(Geo.Position.NEW_POSITION_KEY);
    });
    _$$("center", "both").click(Geo.Position.centerBoth);
    _$$("geocodage").click(_geocodage);
    _$$("actualisation").click(_initAddress);
    _$$("address").keypress(_testAddress).change(_testAddress);
    if (withAdressSource) {
        _initAddress();
    }
    geoPosition = Geo.Position.initMap(geoId + "_map", args.start, _checkCallback);
    
    
    function _validation() {
        let marker = geoPosition.getMarker(Geo.Position.NEW_POSITION_KEY);
        if (marker) {
            let latlng = marker.getLatLng();
            let latElement = window.opener.document.getElementById(args.latitudeId);
            latElement.value = latlng.lat;
            let lonElement =window.opener.document.getElementById(args.longitudeId);
            lonElement.value = latlng.lng;
        }
        window.close();
    }
    
    function _initAddress() {
        let address = "";
        let openerForm = window.opener.document.getElementById(args.latitudeId).form;
        for(let inputName of args.addressArray) {
            let inputElement = openerForm[inputName];
            if (inputElement) {
                let val = inputElement.value;
                if (val) {
                    val = val.trim();
                    if (val.endsWith(";")) {
                        val = val.substring(0, val.length - 1);
                    }
                    val = val.replace(";", ",");
                    if (val.length > 0) {
                        if (address.length > 0) {
                            address = address + ",";
                        }
                        address = address + val;
                    }
                }
            }
        }
        address = Geo.cleanString(address);
        _$$("geocodage").prop("disabled", (address.length === 0));
        _$$("address").val(address);
    }
    
    function _$$(id) {
        if (arguments.length > 1) {
            id = Array.from(arguments).join("_");
        }
        return $$(geoId, id);
    }
    
    function _testAddress() {
        let address = _$$("address").val();
        address = Geo.cleanString(address);
        _$$("geocodage").prop("disabled", (address.length === 0));
    }
    
    function _geocodage() {
        let address = _$$("address").val();
        geoPosition.geocodage(address, function (done) {
            if (!done) {
                alert(Bdf.Loc.get("_ error.unknown.address", address));
            }
        });
    }
    
    function _checkCallback(geoPosition) {
        let  currentActive = geoPosition.hasMarker(Geo.Position.CURRENT_POSITION_KEY);
        let newActive = geoPosition.hasMarker(Geo.Position.NEW_POSITION_KEY);
        _$$("confirm").prop("disabled", !newActive);
        _$$("center", "current").prop("disabled", !currentActive);
        _$$("center", "new").prop("disabled", !newActive);
        _$$("center", "both").prop("disabled", (!currentActive || !newActive));
    }
};

Bdf.addTemplateOptions({
    helpers: {
        credits: function () {
            var text = Bdf.Loc.escape.apply(this, arguments);
            text = text.replace("{NOMINATIM}", "<a href='https://nominatim.openstreetmap.org' target='_blank'>Nominatim</a>");
            text = text.replace("{OPENSTREETMAP}", "<a href='https://www.openstreetmap.org' target='_blank'>OpenStreetMap</a>");
            return text;
        }
    }
});

$(function () {
    Bdf.initTemplates();
    Geo.Geocodage.init(Geo.Geocodage.ARGS);
});