import { Magento2AbstractApiService } from '../magento2.abstract.api.service';

export interface ICategoryProductsResponse {
  attributeValues: Array<any>,
  products: Array<any>
}

/**
 * Service to communicate with the magento2 API
 */
export class WidgetCategoryProductsService extends Magento2AbstractApiService {

  /**
   * Attribute to generate the groups from
   */
  public attribute: string;

  /**
   * URL to the API endpoint
   */
  public url: string = location.hostname;

  constructor(
    public $http,
    public $q,
    public API_URL,
    public API_PRODUCTS_ENDPOINT
  ) {
    super($http, $q, API_URL, API_PRODUCTS_ENDPOINT);
  }

  /**
   * Set the attribute to generate the groups from
   *
   * @param attribute The attribute_code to generate groups from
   */
  public setAttribute(attribute: string): void {
    this.attribute = attribute;
  }

  /**
   * Set the URL to the API endpoint
   *
   * @param attribute The URL to the API endpoint
   */
  public setUrl(url: string): void {
    this.url = url;
  }

  /**
   * Get an observable which returns the requested products
   *
   * @param categories Comma-separated list of category-ids to get products from
   */
  public get(categories: string): Promise<any> {
    return super.get('category_id', categories, 'created_at', 'DESC');
  }

  /**
   * Compute the returned response before passing it to the controller
   *
   * @param res The raw HTTP-Response coming from angularjs
   */
  public prepareResponse(res: any): ICategoryProductsResponse {
    return {
      attributeValues: this.getAttributeValues(res.data.items, this.attribute),
      products: res.data.items
    }
  }

}
