/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {SCPlace} from '@openstapps/core';
import {geoJSON, Map, MapOptions, tileLayer} from 'leaflet';
import {MapProvider} from '../map.provider';

/**
 * The map widget (needs a container with explicit size)
 */
@Component({
  selector: 'stapps-map-widget',
  styleUrls: ['./map-widget.scss'],
  templateUrl: './map-widget.html',
})
export class MapWidgetComponent implements OnInit {
  /**
   * A leaflet map showed
   */
  map: Map;

  /**
   * Container element of the map
   */
  @ViewChild('mapContainer') mapContainer: ElementRef;

  /**
   * Options of the leaflet map
   */
  options: MapOptions;

  /**
   * A place to show on the map
   */
  @Input() place: SCPlace;

  /**
   * Indicates if the expand button should be visible
   */
  showExpandButton = true;

  constructor(private router: Router) {}

  /**
   * Prepare the map
   */
  ngOnInit() {
    const markerLayer = MapProvider.getPointMarker(this.place.geo.point, 'stapps-location', 32);
    this.options = {
      center: geoJSON(this.place.geo.polygon || this.place.geo.point)
        .getBounds()
        .getCenter(),
      layers: [
        tileLayer('https://osm.server.uni-frankfurt.de/tiles/roads/x={x}&y={y}&z={z}', {
          attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
          maxZoom: 18,
        }),
        markerLayer,
      ],
      zoom: 16,
      zoomControl: false,
    };
    if (this.router) {
      this.showExpandButton = !this.router.url.startsWith('/map');
    }
  }

  /**
   * What happens when the leaflet map is ready (note: doesn't mean that tiles are loaded)
   */
  onMapReady(map: Map) {
    this.map = map;
    this.map.dragging.disable();
    const interval = window.setInterval(() => {
      MapProvider.invalidateWhenRendered(map, this.mapContainer, interval);
    });
  }
}
