import {Injectable} from '@angular/core';
import {ISchema, Resource, Service , ICollection} from 'ngx-jsonapi';
import {Service as Srv , ServicesService} from './services.service';
import {Base} from 'ngx-jsonapi/services/base';
import {Type, TypesService} from './type.service';

@Injectable()
export class RequestsService extends Service<Request> {
  public resource = Request;
  public type = 'requests';
  public schema: ISchema = {
    relationships: {
      services: {
        hasMany: true
      } ,
      type: {
        hasMany: false
      },

    }
  };

}

export class Request extends Resource {
  private _attributes: {
    lng: number,
    lat: number,
    sumPrice: number,
    address: string,
  };

  public getLat() {
    return this.attributes.lat;
  }

  public setLat(lat: string) {
    return this.attributes.lat = lat;
  }

  public getLng() {
    return this.attributes.lng;
  }

  public setLng(lng: string) {
    return this.attributes.lng = lng;
  }

  public getSumPrice() {
    return this.attributes.sumPrice;
  }

  public setSumPrice(sumPrice: number) {
    return this.attributes.sumPrice = sumPrice;
  }

  public getAddress() {
    return this.attributes.address;
  }

  public setAddress(address: string) {
    return this.attributes.address = address;
  }

  public getServices(): ICollection<Srv> {
    return <ICollection<Srv>>this.relationships.services.data;
  }

  public getServicesIds(): string[] {
    const ids: string[] = [];
    Base.forEach(this.getServices(), (services: Srv) => {
      ids.push(services.id);
    });
    return ids;
  }

  public setServices(services: ICollection<Srv>) {
    this.relationships.services.data = services;
  }

  public setServicesWithIds(ids: string[]) {

    const selected_Services: ICollection<Srv> = Base.newCollection<Srv>();
    ids.forEach(function (id) {

      const service = (new ServicesService()).new();
      service.id = id;
      selected_Services[id] = service;
    });
    this.setServices(selected_Services);
  }

  public getType(): Type {
    return <Type>this.relationships.type.data;
  }
  public setTypeWithId(id: string) {
    const typeService = new TypesService();
    const type = typeService.new();
    type.id = id;
    this.relationships.type.data = type;
  }

  public getServicePivots(): object[] {
    if (this.relationships.services.meta) {
      return this.relationships.services.meta['pivots'];
    }
  }

  public setServicePivots(services: object[]) {

    this.relationships.services.meta = {};
    this.relationships.services.meta['pivots'] = services;
  }


}
