import {Injectable} from '@angular/core';
import {ICollection, ISchema, Resource, Service} from 'ngx-jsonapi';
import {Universities, UniversitiesService} from './universities.service';
import {Base} from 'ngx-jsonapi/services/base';
import {Cities, CitiesService} from './cities.service';

@Injectable()
export class UnitsService extends Service<Units> {
  public resource = Units;
  public type = 'units';
  public schema: ISchema = {
    relationships: {
      cities: {
        hasMany: true
      },
    }
  };
}

export class Units extends Resource {
  public attributes: {
    name: string,
  };

  get name(): string {
    return this.attributes.name;
  }

  set name(name: string) {
    this.attributes.name = name;
  }

  get cities(): ICollection<Cities> {
    return <ICollection<Cities>>this.relationships.cities.data;
  }

  set cities(cities: ICollection<Cities>) {
    this.relationships.cities.data = cities;
  }

  get citiesIds(): string[] {
    let ids: string[] = [];
    Base.forEach(this.cities, (city: Universities) => {
      ids.push(city.id);
    });
    return ids;
  }

  set citiesIds(cities: string[]) {
    const selected_cities: ICollection<Cities> = Base.newCollection<Cities>();
    for (const key in cities) {
      if (key in cities) {
        const city_id = cities[key];
        const city = (new CitiesService()).new();
        city.id = city_id;
        selected_cities[city_id] = city;
      }
    }
    this.cities = selected_cities;
  }
}
