/*
 * 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, Input, OnInit} from '@angular/core';
import {SCSearchBooleanFilter, SCPlace, SCSearchFilter} from '@openstapps/core';
import {MapProvider} from '../../map.provider';
import {ModalController} from '@ionic/angular';
import {LatLngBounds} from 'leaflet';

/**
 * Modal showing a provided list of places
 */
@Component({
  selector: 'map-list-modal',
  templateUrl: 'map-list.html',
  styleUrls: ['map-list.scss'],
})
export class MapListModalComponent implements OnInit {
  /**
   * Used for creating the search for the shown list
   */
  @Input() filterQuery?: SCSearchFilter;

  /**
   * Map visible boundaries limiting items in lust
   */
  @Input() mapBounds?: LatLngBounds;

  /**
   * Places to show in the list
   */
  items: SCPlace[];

  /**
   * Used for creating the search for the shown list
   */
  @Input() queryText?: string;

  constructor(private mapProvider: MapProvider, readonly modalController: ModalController) {}

  /**
   * Populate the list with the results from the search
   */
  ngOnInit() {
    let geofencedFilter: SCSearchBooleanFilter | undefined;
    if (typeof this.mapBounds !== 'undefined') {
      geofencedFilter = {
        arguments: {
          operation: 'and',
          filters: [
            {
              type: 'geo',
              arguments: {
                field: 'geo',
                shape: {
                  coordinates: [
                    [this.mapBounds.getNorthWest().lng, this.mapBounds.getNorthWest().lat],
                    [this.mapBounds.getSouthEast().lng, this.mapBounds.getSouthEast().lat],
                  ],
                  type: 'envelope',
                },
                spatialRelation: 'intersects',
              },
            },
          ],
        },
        type: 'boolean',
      };
      if (typeof this.filterQuery !== 'undefined') {
        geofencedFilter.arguments.filters.push(this.filterQuery);
      }
    }

    const geofencedFilterQuery = geofencedFilter ?? this.filterQuery;
    this.mapProvider.searchPlaces(geofencedFilterQuery, this.queryText).then(result => {
      this.items = result.data as SCPlace[];
    });
  }
}
