// import { WidgetsProductsService } from './widget.products.service';
import { CarouselAbstractController } from '../../carousel/carousel.abstract.controller';

export class WidgetProductsController extends CarouselAbstractController {

  public url: string;
  public prices: boolean;
  public products: Array<any> = [];
  public configElement: HTMLElement;

  private staticItemsPerPage: any;
  private staticEntityIds: string;
  private staticHeadline: string;

  constructor(
    private WidgetsProductsService,
    private $timeout,
    public $element
  ) {
    super($element);
    this.configElement = this.$element[0].closest('[entity-ids]');
    console.log($element);
  }

  public set entityIds(entityIds) {
    this.staticEntityIds = entityIds;
  }

  public get entityIds() {
    if (!this.staticEntityIds) {
      return this.configElement.getAttribute('entity-ids');
    } else {
      return this.staticEntityIds;
    }
  }

  public set headline(headline) {
    this.staticHeadline = headline;
  }

  public get headline() {
    if (!this.staticHeadline) {
      return this.configElement.getAttribute('headline');
    } else {
      return this.staticHeadline;
    }
  }

  public set itemsPerPage(itemsPerPage) {
    this.staticItemsPerPage = parseInt(itemsPerPage, 10);
  }

  public get itemsPerPage() {
    if (!this.staticItemsPerPage) {
      return parseInt(this.configElement.getAttribute('items-per-page'), 10);
    } else {
      return this.staticItemsPerPage;
    }
  }

  public get slides(): Array<number> {
    let numSlides = Math.ceil(this.products.length / this.itemsPerPage);
    return new Array(numSlides);
  }

  public itemsHelper(index): Array<number> {
    if (this.products.length) {
      let numShould = new Array(this.itemsPerPage);
      let offsetted = this.products.slice(index * this.itemsPerPage);
      if (numShould.length <= offsetted.length) {
        return numShould;
      } else {
        return offsetted;
      }
    } else {
      return [];
    }
  }

  $onInit() {
    super.$onInit();
    if (this.url) {
      this.WidgetsProductsService.setUrl(this.url);
    }
    this.WidgetsProductsService.get(this.entityIds).then(response => {
      if (response.status === 200) {
        this.$timeout(() => {
          this.products = response.data.items;
        }, 0);
      }
    });
  }
}
