/*
 * Copyright (C) 2023 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 {ChangeDetectionStrategy, Component, Input} from '@angular/core';
import {PositionService} from '../../../map/position.service';
import {filter, Observable} from 'rxjs';
import {hasValidLocation, isSCFloor, PlaceTypes, PlaceTypesWithDistance} from './place-types';
import {map} from 'rxjs/operators';
import {trigger, transition, style, animate} from '@angular/animations';

/**
 * Shows a place as a list item
 */
@Component({
  selector: 'stapps-place-list-item',
  templateUrl: 'place-list-item.html',
  styleUrls: ['place-list-item.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [trigger('fade', [transition(':enter', [style({opacity: 0}), animate(100)])])],
})
export class PlaceListItemComponent {
  _item: PlaceTypesWithDistance;

  /**
   * An item to show (setter is used as there were issues assigning the distance to the right place in a list)
   */
  @Input() set item(item: PlaceTypes) {
    this._item = item;
    if (!isSCFloor(item) && hasValidLocation(item)) {
      this.distance = this.positionService.geoLocation.pipe(
        map(
          position =>
            Math.hypot(
              position.coords.latitude - item.geo.point.coordinates[1],
              position.coords.longitude - item.geo.point.coordinates[0],
            ) * 111_139,
        ),
        filter(it => it !== undefined),
      );
    }
  }

  /**
   * Distance in meters
   */
  distance?: Observable<number | undefined>;

  constructor(private positionService: PositionService) {}
}
