/*
 * 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} from '@angular/core';
import {
  SCContactPoint,
  SCContactPointWithoutReferences,
  SCPerson,
  SCSearchQuery,
  SCUuid,
} from '@openstapps/core';
import {DataProvider} from '../../data.provider';

@Component({
  selector: 'stapps-person-detail-content',
  templateUrl: 'person-detail-content.html',
})
export class PersonDetailContentComponent {
  private _item: SCPerson;

  contactPoints: Array<SCContactPoint | SCContactPointWithoutReferences>;

  get item(): SCPerson {
    return this._item;
  }

  @Input() set item(item: SCPerson) {
    this._item = item;
    if (item.workLocations) {
      this.contactPoints = item.workLocations;
      this.getContactPoints(item.workLocations).then(contactPoints => {
        this.contactPoints = contactPoints;
      });
    }
  }

  constructor(private readonly dataProvider: DataProvider) {}

  async getContactPoints(workLocations: SCContactPointWithoutReferences[]): Promise<SCContactPoint[]> {
    const query: {[uid in SCUuid]: SCSearchQuery} = {};
    workLocations.map(workLocation => {
      query[workLocation.uid] = {
        filter: {
          arguments: {
            field: 'uid',
            value: workLocation.uid,
          },
          type: 'value',
        },
      };
    });

    const contactPoints: SCContactPoint[] = Object.values(await this.dataProvider.multiSearch(query)).map(
      result => result.data[0] as SCContactPoint,
    );

    return contactPoints;
  }

  isContactPoint(
    contactPoint: SCContactPoint | SCContactPointWithoutReferences,
  ): contactPoint is SCContactPoint {
    return 'areaServed' in contactPoint;
  }
}
