import { IController, IScope } from 'angular';
import { Magento2ProductAttributesApiService } from './magento2.product.attributes.api.service';
import { IMagento2Attribute, IMagento2AttributeOption } from './magento2.attribute';


/**
 * Controller holding the application-logic for <attributes-component>
 */
export class AttributesController implements IController {

  public options: IMagento2AttributeOption[] = [];

  private readonly categoryUrl: string;
  private _identifier: string;

  private static appendSearch(url: string, key: string, par: string|number) {
    let glue = url.indexOf('?') > -1 ? '&' : '?';
    let hash = url.indexOf('#') > -1 ? url.slice(url.indexOf('#')) : '';
    key = encodeURIComponent(key);
    par = encodeURIComponent(par as string);

    return `${url}${glue}${key}=${par}${hash}`;
  }

  constructor(
    public $element: JQLite,
    private readonly $scope: IScope,
    private readonly magento2ProductAttributesApiService: Magento2ProductAttributesApiService
  ) {
    if ($element.attr('categoryUrl')) {
      this.categoryUrl = $element.attr('categoryUrl');
    } else if ('categoryUrl' in $scope) {
      this.categoryUrl = ($scope as any).categoryUrl;
    } else if ($scope.$parent && 'categoryUrl' in $scope.$parent) {
      this.categoryUrl = ($scope.$parent as any).categoryUrl;
    } else {
      this.categoryUrl = location.protocol + '//' + location.host;
    }
  }

  private fetch() {
    this.magento2ProductAttributesApiService
      .get(this._identifier)
      .then((attribute: IMagento2Attribute) => {
        angular.forEach(attribute.options, (option) => {
          if (option.label.replace(/ +/, ' ').length === 0
              || option.value.replace(/ +/, ' ').length === 0) {
            return;
          }

          if (!('url' in option && option.url)) {
            option.url = AttributesController.appendSearch(this.categoryUrl, this._identifier, option.value);
          }

          this.options.push(option);
        });
      })
    ;
  }

  public set identifier(identifier) {
    if (!this._identifier) {
      this._identifier = identifier;
      if (this._identifier) {
        this.fetch();
      }
    }
  }

  public get identifier() {
    return this._identifier;
  }
}
