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


@Injectable()
export class ServicesService extends Srv<Service> {
  public resource = Service;
  public type = 'services';
  public schema: ISchema = {
    relationships: {
      types: {
        hasMany: true
      },
      products: {
        hasMany: true
      }
    }
  };
}

export class Service extends Resource {
  public attributes: {
    name: string,
    price: number,
  };

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

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

  get price(): number {
    return this.attributes.price;
  }

  set price(price: number) {
    this.attributes.price = price;
  }

  //  in baray relationship type hast ke  chand be chande
  get types(): ICollection<Type> {
    return <ICollection<Type>>this.relationships.types.data;
  }

  set types(types: ICollection<Type>) {
    this.relationships.types.data = types;
  }

  get typesIds(): string[] {
    let ids: string[] = [];
    Base.forEach(this.types, (type: Type) => {
      ids.push(type.id);
    });
    return ids;
  }

  set typesIds(ids: string[]) {
    let selected_types: ICollection<Type> = Base.newCollection<Type>();
    ids.forEach(function (id) {
      let type = (new TypesService()).new();
      type.id = id;
      selected_types[id] = type;
    });
    this.types = selected_types;
  }


//  in baray relation product hast ke chand be chand hast
  get products(): ICollection<Product> {
    console.log('zahra',this.relationships.products.data) ;

    return <ICollection<Product>>this.relationships.products.data;
  }

  set products(Product: ICollection<Product>) {
    this.relationships.products.data = Product;
  }

  get productsIds(): string[] {
    let ids: string[] = [];
    Base.forEach(this.products, (products: Product) => {
      ids.push(products.id);
    });
    return ids;
  }

  set productsIds(ids: string[]) {
    let selected_products: ICollection<Product> = Base.newCollection<Product>();
    ids.forEach(function (id) {
      let product = (new ProductsService()).new();
      product.id = id;
      selected_products[id] = product;
    });
    this.products = selected_products;
  }
}
