import { IController } from 'angular';
import {
  CarouselAbstractController
} from '../../carousel/carousel.abstract.controller';
// import { WidgetCategoryProductsService } from './widget.category.products.service';
import ScreenSizeDetection from '../../ScreenSizeDetection';

type CategoryProductsMode = 'tabs' | 'carousel';

export
  class WidgetCategoryProductsController
  extends CarouselAbstractController
  implements IController {

  private staticCategories: string;
  private staticAttribute: string;
  private staticHeadline: string;

  public url: string;
  public prices: boolean;
  public attributeValues: Array<string>;
  public productsRaw: Array<any> = [];
  public selectedAttributeValue: string;
  public mode: CategoryProductsMode;
  public carouselElement: any;
  public listElement: any;
  public screensize: string;
  public sliceList: number;
  public stepLength: number;
  private scrollContainer: Element;

  constructor(
    private WidgetCategoryProductsService,
    private $timeout,
    public $element
  ) {
    super($timeout);
  }

  private subscribeScreenSize() {
    ScreenSizeDetection.get().subscribe(screensize => {
      this.$timeout(() => {
        this.screensize = screensize;
        this.setMode();
        this.calculateHeight();
      });
    });
  }

  public set categories(categories) {
    let staticCategoriesSetBefore = this.staticCategories;
    this.staticCategories = categories;
    if (staticCategoriesSetBefore) {
      this.getData()
    };
  }

  public get categories() {
    if (!this.staticCategories) {
      return this.$element[0].parentNode.getAttribute('categories');
    } else {
      return this.staticCategories;
    }
  }

  public set attribute(attribute) {
    this.staticAttribute = attribute;
  }

  public get attribute() {
    if (!this.staticAttribute) {
      return this.$element[0].parentNode.getAttribute('attribute');
    } else {
      return this.staticAttribute;
    }
  }

  public set headline(attribute) {
    this.staticAttribute = attribute;
  }

  public get headline() {
    if (!this.staticHeadline) {
      return this.$element[0].parentNode.getAttribute('headline');
    } else {
      return this.staticHeadline;
    }
  }

  private calculateHeight(): void {
    let rowsVisible = 2;
    let firstItem = this.listElement[0].querySelector('li');
    if (this.mode === 'carousel') {
      this.sliceList = 0;
    } else if (firstItem) {
      let singleWidth = parseInt(
        window.getComputedStyle(firstItem, null).getPropertyValue('max-width'),
        10
      );
      let elementsPerRow = 100 / singleWidth;
      this.stepLength = elementsPerRow * rowsVisible;
      this.sliceList = this.stepLength;
    }
  }

  private setMode(): void {
    if (this.screensize === 'xs' || this.screensize === 'sm') {
      this.mode = 'carousel';
      this.$timeout(this.initCarousel.bind(this));
    } else {
      this.mode = 'tabs';
    }
  }

  private getData(): void {
    this.WidgetCategoryProductsService.get(this.categories).then((data) => {
      data.attributeValues.unshift('all');
      this.attributeValues = data.attributeValues;
      this.selectedAttributeValue = this.attributeValues[0];
      this.productsRaw = data.products;
      this.$timeout(() => {
        this.calculateHeight();
      });
    });
  }

  public 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) {
            return false;
          }

          if (attribute.value instanceof Array) {
            return attribute.value.indexOf(this.selectedAttributeValue) !== -1;
          } else {
            return attribute.value === this.selectedAttributeValue
          }
        });
        return result.length;
      });
    }
    return (this.sliceList) ? list.slice(0, this.sliceList) : list;
  }

  public toggleList(): void {
    if (this.sliceList) {
      this.sliceList = 0;
    } else {
      this.scrollContainer.scrollTo(0, this.$element[0].offsetTop);
      this.sliceList = this.stepLength;
    }
  }

  public getToggleButtonText(): string {
    if (this.sliceList) {
      return 'Alle Anzeigen';
    } else {
      return 'Weniger Anzeigen';
    }
  }

  public getToggleButtonIcon(): string {
    if (this.sliceList) {
      return 'plus';
    } else {
      return 'minus';
    }
  }

  public getAttribute(product: any, attribute_code: string): string {
    let result = product.custom_attributes.find((item) => {
      return item.attribute_code === attribute_code;
    });
    if (result) {
      return result.value;
    } else {
      return '';
    }
  }

  public setActive(attributeValue: string): void {
    this.selectedAttributeValue = attributeValue;
  }

  public $onInit(): void {
    this.scrollContainer = document.querySelector('.styleguide-content');
    if (!this.scrollContainer) {
      this.scrollContainer = document.body;
    }
    if (this.url) {
      this.WidgetCategoryProductsService.setUrl(this.url);
    }
    this.WidgetCategoryProductsService.setAttribute(this.attribute);
    this.listElement = this.$element.find('.product-items');
    this.getData();
    this.subscribeScreenSize();
  }
}
