import { Component, ViewChild } from '@angular/core';
import { MapComponent } from '@c8y/ngx-components/map';
import { AlertService, ContextRouteService, OptionsService, Permissions, gettext } from '@c8y/ngx-components';
import { ActivatedRoute } from '@angular/router';
import { InventoryService } from '@c8y/client';
import { isUndefined, cloneDeep } from 'lodash-es';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import * as i0 from "@angular/core";
import * as i1 from "@c8y/ngx-components";
import * as i2 from "@angular/router";
import * as i3 from "@c8y/client";
import * as i4 from "@c8y/ngx-components/map";
import * as i5 from "@angular/common";
import * as i6 from "@angular/forms";
export class LocationComponent {
    constructor(contextRouteService, activatedRoute, inventoryService, permissions, optionsService, alertService) {
        this.contextRouteService = contextRouteService;
        this.activatedRoute = activatedRoute;
        this.inventoryService = inventoryService;
        this.permissions = permissions;
        this.optionsService = optionsService;
        this.alertService = alertService;
        this.isEdit = false;
        this.canEdit = true;
        this.config = { realtime: false, follow: true, zoomLevel: 12 };
        this.addressSearchTerm = '';
        this.hideAddressSearchFeature = false;
        this.destroy$ = new Subject();
        this.mapNominatimUrl = 'https://nominatim.openstreetmap.org/search?format=json&q={searchTerm}';
    }
    ngOnInit() {
        this.activatedRoute.url.pipe(takeUntil(this.destroy$)).subscribe(() => {
            this.updateMap();
        });
    }
    async updateMap() {
        const { contextData } = this.contextRouteService.getContextData(this.activatedRoute);
        this.position = contextData;
        this.canEdit = await this.permissions.canEdit([Permissions.ROLE_INVENTORY_ADMIN, Permissions.ROLE_INVENTORY_CREATE], contextData);
        const hasCustomSetting = !isUndefined(this.optionsService.mapNominatimUrl);
        this.hideAddressSearchFeature = hasCustomSetting && !this.optionsService.mapNominatimUrl;
        if (hasCustomSetting) {
            this.mapNominatimUrl = this.optionsService.mapNominatimUrl;
        }
        this.map.refresh();
    }
    toggleRealtime() {
        this.config = { ...this.config, realtime: !this.config.realtime };
    }
    disableRealtime() {
        this.config = { ...this.config, realtime: false };
    }
    centerMap() {
        this.config = {
            ...this.config,
            center: [this.position.c8y_Position.lat, this.position.c8y_Position.lng]
        };
    }
    edit() {
        this.originalPosition = cloneDeep(this.position);
        this.enableMarkerDragging();
        this.disableRealtime();
        this.isEdit = true;
    }
    cancel() {
        this.position = this.originalPosition;
        this.isEdit = false;
        this.map.markers[0]?.dragging.disable();
        this.centerMap();
    }
    async save() {
        try {
            const { data } = await this.inventoryService.update({
                id: this.position.id,
                c8y_Position: this.position.c8y_Position
            });
            this.position = data;
        }
        catch (ex) {
            this.alertService.addServerFailure(ex);
        }
        this.map.markers[0]?.dragging.disable();
        this.centerMap();
        this.isEdit = false;
    }
    positionChanged(position) {
        this.position = position;
    }
    async searchAddress(searchTerm) {
        const fetchResponse = await fetch(this.mapNominatimUrl.replace('{searchTerm}', searchTerm));
        if (fetchResponse.status !== 200) {
            this.alertService.danger(gettext('Failed to search for address.'));
            return;
        }
        const data = await fetchResponse.json();
        const latLng = data[0];
        if (!latLng) {
            this.alertService.warning(gettext('Address could not be found.'));
            return;
        }
        this.position.c8y_Position.lat = Number(latLng.lat);
        this.position.c8y_Position.lng = Number(latLng.lon);
        this.updateMarkerPosition();
        if (latLng.licence) {
            this.map.map.attributionControl.addAttribution(latLng.licence);
        }
    }
    updateMarkerPosition() {
        this.map.refreshMarkers();
        this.enableMarkerDragging();
        this.centerMap();
    }
    ngOnDestroy() {
        this.destroy$.next();
    }
    enableMarkerDragging() {
        const marker = this.map.markers[0];
        if (marker) {
            marker.dragging.enable();
            marker.on('dragend', () => {
                const latlng = marker.getLatLng();
                this.position.c8y_Position = {
                    ...this.position.c8y_Position,
                    lat: latlng.lat,
                    lng: latlng.lng
                };
                this.centerMap();
            });
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: LocationComponent, deps: [{ token: i1.ContextRouteService }, { token: i2.ActivatedRoute }, { token: i3.InventoryService }, { token: i1.Permissions }, { token: i1.OptionsService }, { token: i1.AlertService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.9", type: LocationComponent, selector: "c8y-location", viewQueries: [{ propertyName: "map", first: true, predicate: MapComponent, descendants: true }], ngImport: i0, template: "<c8y-action-bar-item placement=\"right\">\n  <button\n    class=\"btn btn-link c8y-realtime\"\n    title=\"{{ 'Toggle realtime' | translate }}\"\n    type=\"button\"\n    (click)=\"toggleRealtime()\"\n  >\n    <span\n      class=\"c8y-pulse\"\n      [ngClass]=\"{ active: config.realtime, inactive: !config.realtime }\"\n    ></span>\n    <span translate>Realtime</span>\n  </button>\n</c8y-action-bar-item>\n<c8y-action-bar-item placement=\"right\">\n  <button\n    class=\"btn btn-clean\"\n    title=\"{{ 'Center`verb`' | translate }}\"\n    (click)=\"centerMap()\"\n  >\n    <i [c8yIcon]=\"'target1'\"></i>\n    <span translate>Center`verb`</span>\n  </button>\n</c8y-action-bar-item>\n\n<div class=\"card card--grid content-fullpage d-grid grid__col--8-4--md\">\n  <div\n    class=\"bg-white p-relative\"\n    style=\"min-height: 30vh\"\n  >\n    <c8y-map\n      [assets]=\"[position]\"\n      [config]=\"config\"\n      (onRealtimeUpdate)=\"positionChanged($event)\"\n    ></c8y-map>\n  </div>\n\n  <form\n    class=\"d-flex d-col bg-inherit content-fullpage bg-gray-white\"\n    #positionForm=\"ngForm\"\n    (ngSubmit)=\"save()\"\n  >\n    <div class=\"card-header large-padding separator sticky-top\">\n      <span\n        class=\"card-title\"\n        translate\n      >\n        Device location\n      </span>\n    </div>\n    <div class=\"inner-scroll\">\n      <div\n        class=\"m-16\"\n        *ngIf=\"!isEdit\"\n      >\n        <div class=\"p-b-40\">\n          <div\n            class=\"text-bold\"\n            translate\n          >\n            Latitude (\u00B0)\n          </div>\n          {{ position.c8y_Position.lat }}\n        </div>\n        <div class=\"p-b-40\">\n          <div\n            class=\"text-bold\"\n            translate\n          >\n            Longitude (\u00B0)\n          </div>\n          {{ position.c8y_Position.lng }}\n        </div>\n        <div class=\"p-b-40\">\n          <div\n            class=\"text-bold\"\n            translate\n          >\n            Altitude (m)\n          </div>\n          {{ position.c8y_Position.alt }}\n        </div>\n      </div>\n      <div\n        class=\"m-16\"\n        *ngIf=\"isEdit\"\n      >\n        <c8y-form-group>\n          <label\n            for=\"lat\"\n            translate\n          >\n            Latitude (\u00B0)\n          </label>\n\n          <input\n            class=\"form-control\"\n            [title]=\"'Latitude (\u00B0)' | translate\"\n            id=\"lat\"\n            name=\"lat\"\n            type=\"number\"\n            required\n            min=\"-90\"\n            max=\"90\"\n            (blur)=\"updateMarkerPosition()\"\n            [(ngModel)]=\"position.c8y_Position.lat\"\n          />\n          <c8y-messages>\n            <c8y-message\n              name=\"min\"\n              [text]=\"'The minimum latitude value is -90\u00B0.' | translate\"\n            ></c8y-message>\n            <c8y-message\n              name=\"max\"\n              [text]=\"'The maximum latitude value is 90\u00B0.' | translate\"\n            ></c8y-message>\n          </c8y-messages>\n        </c8y-form-group>\n        <c8y-form-group>\n          <label\n            for=\"lat\"\n            translate\n          >\n            Longitude (\u00B0)\n          </label>\n\n          <input\n            class=\"form-control\"\n            [title]=\"'Longitude (\u00B0)' | translate\"\n            id=\"lng\"\n            name=\"lng\"\n            type=\"number\"\n            required\n            min=\"-180\"\n            max=\"180\"\n            (blur)=\"updateMarkerPosition()\"\n            [(ngModel)]=\"position.c8y_Position.lng\"\n          />\n          <c8y-messages>\n            <c8y-message\n              name=\"min\"\n              [text]=\"'The minimum longitude value is -180\u00B0.' | translate\"\n            ></c8y-message>\n            <c8y-message\n              name=\"max\"\n              [text]=\"'The maximum longitude value is 180\u00B0.' | translate\"\n            ></c8y-message>\n          </c8y-messages>\n        </c8y-form-group>\n        <c8y-form-group>\n          <label\n            for=\"alt\"\n            translate\n          >\n            Altitude (m)\n          </label>\n\n          <input\n            class=\"form-control\"\n            [title]=\"'Altitude (m)' | translate\"\n            id=\"alt\"\n            name=\"alt\"\n            type=\"number\"\n            [(ngModel)]=\"position.c8y_Position.alt\"\n          />\n        </c8y-form-group>\n      </div>\n\n      <form\n        class=\"card-block bg-level-1\"\n        #addressSearch=\"ngForm\"\n        novalidate\n        (submit)=\"searchAddress(addressSearchTerm)\"\n        *ngIf=\"isEdit && !hideAddressSearchFeature\"\n      >\n        <div class=\"form-group\">\n          <label\n            for=\"searchAddress\"\n            translate\n          >\n            Find lat/long by address\n          </label>\n          <div class=\"input-group input-group-search\">\n            <input\n              class=\"form-control\"\n              id=\"searchAddress\"\n              name=\"addressSearchTerm\"\n              type=\"text\"\n              [placeholder]=\"'e.g. Speditionstra\u00DFe 13, D\u00FCsseldorf`LOCALIZE`' | translate\"\n              [(ngModel)]=\"addressSearchTerm\"\n            />\n            <span class=\"input-group-btn\">\n              <button\n                class=\"btn btn-dot\"\n                [title]=\"'Search' | translate\"\n                type=\"submit\"\n              >\n                <i\n                  class=\"dlt-c8y-icon-search\"\n                  c8y-icon=\"search\"\n                ></i>\n              </button>\n            </span>\n          </div>\n        </div>\n      </form>\n    </div>\n    <div class=\"card-footer separator\">\n      <button\n        class=\"btn btn-default\"\n        [title]=\"'Edit location' | translate\"\n        type=\"button\"\n        *ngIf=\"canEdit && !isEdit\"\n        (click)=\"edit()\"\n        translate\n      >\n        Edit location\n      </button>\n      <button\n        class=\"btn btn-default\"\n        [title]=\"'Cancel' | translate\"\n        type=\"button\"\n        (click)=\"cancel()\"\n        *ngIf=\"isEdit\"\n        translate\n      >\n        Cancel\n      </button>\n      <button\n        class=\"btn btn-primary\"\n        [title]=\"'Save' | translate\"\n        type=\"submit\"\n        *ngIf=\"isEdit\"\n        translate\n        [disabled]=\"!positionForm.valid\"\n      >\n        Save\n      </button>\n    </div>\n  </form>\n</div>\n", dependencies: [{ kind: "component", type: i4.MapComponent, selector: "c8y-map", inputs: ["config", "assets", "polyline$", "polylineOptions"], outputs: ["onRealtimeUpdate", "onMove", "onMoveEnd", "onZoomStart", "onZoomEnd", "onMap", "onInit"] }, { kind: "component", type: i1.ActionBarItemComponent, selector: "c8y-action-bar-item", inputs: ["placement", "priority", "itemClass", "injector", "groupId", "inGroupPriority"] }, { kind: "directive", type: i1.IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "directive", type: i1.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i5.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i5.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.MinValidationDirective, selector: "[min]", inputs: ["min"] }, { kind: "directive", type: i1.MaxValidationDirective, selector: "[max]", inputs: ["max"] }, { kind: "directive", type: i6.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i6.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i6.NumberValueAccessor, selector: "input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]" }, { kind: "directive", type: i6.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i6.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i6.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i6.MinValidator, selector: "input[type=number][min][formControlName],input[type=number][min][formControl],input[type=number][min][ngModel]", inputs: ["min"] }, { kind: "directive", type: i6.MaxValidator, selector: "input[type=number][max][formControlName],input[type=number][max][formControl],input[type=number][max][ngModel]", inputs: ["max"] }, { kind: "directive", type: i6.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i6.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "component", type: i1.FormGroupComponent, selector: "c8y-form-group", inputs: ["hasError", "hasWarning", "hasSuccess", "novalidation", "status"] }, { kind: "directive", type: i1.MessageDirective, selector: "c8y-message", inputs: ["name", "text"] }, { kind: "component", type: i1.MessagesComponent, selector: "c8y-messages", inputs: ["show", "defaults", "helpMessage"] }, { kind: "directive", type: i1.RequiredInputPlaceholderDirective, selector: "input[required], input[formControlName]" }, { kind: "pipe", type: i1.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: LocationComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-location', template: "<c8y-action-bar-item placement=\"right\">\n  <button\n    class=\"btn btn-link c8y-realtime\"\n    title=\"{{ 'Toggle realtime' | translate }}\"\n    type=\"button\"\n    (click)=\"toggleRealtime()\"\n  >\n    <span\n      class=\"c8y-pulse\"\n      [ngClass]=\"{ active: config.realtime, inactive: !config.realtime }\"\n    ></span>\n    <span translate>Realtime</span>\n  </button>\n</c8y-action-bar-item>\n<c8y-action-bar-item placement=\"right\">\n  <button\n    class=\"btn btn-clean\"\n    title=\"{{ 'Center`verb`' | translate }}\"\n    (click)=\"centerMap()\"\n  >\n    <i [c8yIcon]=\"'target1'\"></i>\n    <span translate>Center`verb`</span>\n  </button>\n</c8y-action-bar-item>\n\n<div class=\"card card--grid content-fullpage d-grid grid__col--8-4--md\">\n  <div\n    class=\"bg-white p-relative\"\n    style=\"min-height: 30vh\"\n  >\n    <c8y-map\n      [assets]=\"[position]\"\n      [config]=\"config\"\n      (onRealtimeUpdate)=\"positionChanged($event)\"\n    ></c8y-map>\n  </div>\n\n  <form\n    class=\"d-flex d-col bg-inherit content-fullpage bg-gray-white\"\n    #positionForm=\"ngForm\"\n    (ngSubmit)=\"save()\"\n  >\n    <div class=\"card-header large-padding separator sticky-top\">\n      <span\n        class=\"card-title\"\n        translate\n      >\n        Device location\n      </span>\n    </div>\n    <div class=\"inner-scroll\">\n      <div\n        class=\"m-16\"\n        *ngIf=\"!isEdit\"\n      >\n        <div class=\"p-b-40\">\n          <div\n            class=\"text-bold\"\n            translate\n          >\n            Latitude (\u00B0)\n          </div>\n          {{ position.c8y_Position.lat }}\n        </div>\n        <div class=\"p-b-40\">\n          <div\n            class=\"text-bold\"\n            translate\n          >\n            Longitude (\u00B0)\n          </div>\n          {{ position.c8y_Position.lng }}\n        </div>\n        <div class=\"p-b-40\">\n          <div\n            class=\"text-bold\"\n            translate\n          >\n            Altitude (m)\n          </div>\n          {{ position.c8y_Position.alt }}\n        </div>\n      </div>\n      <div\n        class=\"m-16\"\n        *ngIf=\"isEdit\"\n      >\n        <c8y-form-group>\n          <label\n            for=\"lat\"\n            translate\n          >\n            Latitude (\u00B0)\n          </label>\n\n          <input\n            class=\"form-control\"\n            [title]=\"'Latitude (\u00B0)' | translate\"\n            id=\"lat\"\n            name=\"lat\"\n            type=\"number\"\n            required\n            min=\"-90\"\n            max=\"90\"\n            (blur)=\"updateMarkerPosition()\"\n            [(ngModel)]=\"position.c8y_Position.lat\"\n          />\n          <c8y-messages>\n            <c8y-message\n              name=\"min\"\n              [text]=\"'The minimum latitude value is -90\u00B0.' | translate\"\n            ></c8y-message>\n            <c8y-message\n              name=\"max\"\n              [text]=\"'The maximum latitude value is 90\u00B0.' | translate\"\n            ></c8y-message>\n          </c8y-messages>\n        </c8y-form-group>\n        <c8y-form-group>\n          <label\n            for=\"lat\"\n            translate\n          >\n            Longitude (\u00B0)\n          </label>\n\n          <input\n            class=\"form-control\"\n            [title]=\"'Longitude (\u00B0)' | translate\"\n            id=\"lng\"\n            name=\"lng\"\n            type=\"number\"\n            required\n            min=\"-180\"\n            max=\"180\"\n            (blur)=\"updateMarkerPosition()\"\n            [(ngModel)]=\"position.c8y_Position.lng\"\n          />\n          <c8y-messages>\n            <c8y-message\n              name=\"min\"\n              [text]=\"'The minimum longitude value is -180\u00B0.' | translate\"\n            ></c8y-message>\n            <c8y-message\n              name=\"max\"\n              [text]=\"'The maximum longitude value is 180\u00B0.' | translate\"\n            ></c8y-message>\n          </c8y-messages>\n        </c8y-form-group>\n        <c8y-form-group>\n          <label\n            for=\"alt\"\n            translate\n          >\n            Altitude (m)\n          </label>\n\n          <input\n            class=\"form-control\"\n            [title]=\"'Altitude (m)' | translate\"\n            id=\"alt\"\n            name=\"alt\"\n            type=\"number\"\n            [(ngModel)]=\"position.c8y_Position.alt\"\n          />\n        </c8y-form-group>\n      </div>\n\n      <form\n        class=\"card-block bg-level-1\"\n        #addressSearch=\"ngForm\"\n        novalidate\n        (submit)=\"searchAddress(addressSearchTerm)\"\n        *ngIf=\"isEdit && !hideAddressSearchFeature\"\n      >\n        <div class=\"form-group\">\n          <label\n            for=\"searchAddress\"\n            translate\n          >\n            Find lat/long by address\n          </label>\n          <div class=\"input-group input-group-search\">\n            <input\n              class=\"form-control\"\n              id=\"searchAddress\"\n              name=\"addressSearchTerm\"\n              type=\"text\"\n              [placeholder]=\"'e.g. Speditionstra\u00DFe 13, D\u00FCsseldorf`LOCALIZE`' | translate\"\n              [(ngModel)]=\"addressSearchTerm\"\n            />\n            <span class=\"input-group-btn\">\n              <button\n                class=\"btn btn-dot\"\n                [title]=\"'Search' | translate\"\n                type=\"submit\"\n              >\n                <i\n                  class=\"dlt-c8y-icon-search\"\n                  c8y-icon=\"search\"\n                ></i>\n              </button>\n            </span>\n          </div>\n        </div>\n      </form>\n    </div>\n    <div class=\"card-footer separator\">\n      <button\n        class=\"btn btn-default\"\n        [title]=\"'Edit location' | translate\"\n        type=\"button\"\n        *ngIf=\"canEdit && !isEdit\"\n        (click)=\"edit()\"\n        translate\n      >\n        Edit location\n      </button>\n      <button\n        class=\"btn btn-default\"\n        [title]=\"'Cancel' | translate\"\n        type=\"button\"\n        (click)=\"cancel()\"\n        *ngIf=\"isEdit\"\n        translate\n      >\n        Cancel\n      </button>\n      <button\n        class=\"btn btn-primary\"\n        [title]=\"'Save' | translate\"\n        type=\"submit\"\n        *ngIf=\"isEdit\"\n        translate\n        [disabled]=\"!positionForm.valid\"\n      >\n        Save\n      </button>\n    </div>\n  </form>\n</div>\n" }]
        }], ctorParameters: () => [{ type: i1.ContextRouteService }, { type: i2.ActivatedRoute }, { type: i3.InventoryService }, { type: i1.Permissions }, { type: i1.OptionsService }, { type: i1.AlertService }], propDecorators: { map: [{
                type: ViewChild,
                args: [MapComponent]
            }] } });
//# sourceMappingURL=data:application/json;base64, 