export type Direction = 'ASC' | 'DESC';
export type OrderBy = 'id' | 'sku' | 'name' | 'price' | 'status' | 'visibility' | 'type_id' | 'created_at' | 'updated_at' | 'weight';

export abstract class Magento2AbstractApiService {

  constructor(
    public $http,
    public $q,
    public API_URL,
    public API_ENDPOINT
  ) {}

  public get(
    field: string,
    values: string,
    orderBy: OrderBy,
    orderDirection: Direction,
    conditionType: string = 'in',
    pageSize: string = '120',
    currentPage: string = '1'
  ): Promise<any> {
    let deferred = this.$q.defer();
    this.$http
        .get(`${this.API_URL}/${this.API_ENDPOINT}`, {
          params: this.getSearchParams(
            field,
            values,
            orderBy,
            orderDirection,
            conditionType,
            pageSize,
            currentPage
          )
        })
        .then((res) => {
          deferred.resolve(
            this.prepareResponse(res)
          );
        });
    return deferred.promise;
  }

  public prepareResponse(res: any): any {
    return res;
  }

  public getSearchParams(
    field: string,
    value: string,
    orderBy: OrderBy,
    orderDirection: Direction,
    conditionType: string = 'in',
    pageSize: string = '120',
    currentPage: string = '1'
  ): any {
    let params = {
      'searchCriteria[filterGroups][0][filters][0][field]': field,
      'searchCriteria[filterGroups][0][filters][0][value]': value,
      'searchCriteria[filterGroups][0][filters][0][conditionType]': conditionType,
      'searchCriteria[sortOrders][0][field]': orderBy,
      'searchCriteria[sortOrders][0][direction]': orderDirection,
      'searchCriteria[pageSize]': pageSize,
      'searchCriteria[currentPage]': currentPage
    };
    return params;
  }

  public getAttributeValues(products: Array<any>, attributeName: string): Array<any> {
    let values = [];
    for (let product of products) {
      let tabAttribute = product.custom_attributes.find((attribute) => {
        return attribute.attribute_code === attributeName;
      });
      if (!tabAttribute) {
        continue
      };

      let productValue = tabAttribute.value;
      if (productValue instanceof Array) {
        for (let singleProductValue of productValue) {
          this.addToArray(values, singleProductValue);
        }
      } else {
        this.addToArray(values, productValue);
      }
    }
    return values;
  }

  public addToArray(data: Array<any>, value: string) {
    if (data.indexOf(value) === -1 && value) {
      data.push(value);
    }
  }
}
