import {Injectable} from '@angular/core';
import {ICollection, ISchema, Resource, Service} from 'ngx-jsonapi';
import {Majore, MajoreService} from './majore.service';
import {Base} from 'ngx-jsonapi/services/base';
import {Units} from './units.service';

@Injectable()
export class UniversitiesService extends Service<Universities> {
  public resource = Universities;
  public type = 'universities';
  public schema: ISchema = {
    relationships: {
      units: {
        hasMany: true
      }
    }
  };
}

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

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

  set name(name: string) {
    this.attributes.name = name;
  }
  get units(): ICollection<Units> {
    return <ICollection<Units>>this.relationships.units.data;
  }

  set units(units: ICollection<Units>) {
    this.relationships.units.data = units;
  }

  get unitsIds(): string[] {
    let ids: string[] = [];
    Base.forEach(this.units, (units: Units) => {
      ids.push(units.id);
    });
    return ids;
  }

  set unitsIds(unitsIds: string[]) {
    if (unitsIds == null) {
      unitsIds = [];
    }
    const selected_units: ICollection<Units> = Base.newCollection<Units>();
    for (const key in unitsIds) {
      if (key in unitsIds) {
        const units_id = unitsIds[key];
        const units = (new MajoreService()).new();
        units.id = units_id;
        selected_units[units_id] = units_id;
      }
    }
    this.units = selected_units;
  }

}
