export class SparepartsController {

  private attributeValues;
  private selectedAttributeValue;
  private productsRaw;
  private attribute: string = 'kopfhoerermodell';

  public itemsPerPage: number = 12;
  public headline: string = 'SPAREPARTS';

  constructor(
    private SparepartsService
  ) {}

  private getData(): void {
    this.SparepartsService.get('1466').then(data => {
      data.attributeValues.unshift('all');
      this.attributeValues = data.attributeValues;
      this.selectedAttributeValue = this.attributeValues[0];
      this.productsRaw = data.products;
    });
  }

  get products(): Array<any> {
    let list;
    if (!this.selectedAttributeValue || this.selectedAttributeValue === 'all') {
      list =  this.productsRaw;
    } else {
      list = this.productsRaw.filter((product) => {
        let result = product.custom_attributes.filter((attribute) => {
          if (attribute.attribute_code === this.attribute) {
            if (attribute.value instanceof Array) {
              return attribute.value.indexOf(this.selectedAttributeValue) !== -1;
            } else {
              return attribute.value === this.selectedAttributeValue;
            }
          }
        });
        return result.length;
      });
    }

    return list;
  }

  $onInit() {
    this.getData();
  }
}
