import { IDeferred, IHttpService, IQService } from 'angular';
import { IPromise } from 'q';
import { Magento2ApiService } from '../Magento2ApiService';
import { IMagento2Block, Magento2Block } from './magento2.block';

export class Magento2EcmsBlockApiService extends Magento2ApiService<IMagento2Block> {

  private static _checkValidIdentifier(identifier): void {
    if (identifier == null || identifier === '') {
      throw new TypeError('Identifier cannot be empty.');
    }
  }

  constructor(
    public $http: IHttpService,
    public $q: IQService,
    public API_URL: string,
    public API_ECMS_BLOCK_ENDPOINT: string
  ) {
    super($http, $q, API_URL, API_ECMS_BLOCK_ENDPOINT);
  }

  public get(
    identifier: string
  ): IPromise<IMagento2Block> {
    Magento2EcmsBlockApiService._checkValidIdentifier(identifier);

    let deferred = this.$q.defer() as IDeferred<IMagento2Block>;
    this._get(identifier)
      .then((data) => {
        deferred.resolve(new Magento2Block(data));
      });

    return deferred.promise;
  }

  public getContent(
    identifier: string
  ): IPromise<string> {
    Magento2EcmsBlockApiService._checkValidIdentifier(identifier);

    return this._get(`${identifier}/content`);
  }
}
