import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

// Helpers
import { HelperService } from './svc.helper';

@Injectable()
export class MaterialService {

    result: any;

    constructor(
        private http: Http,
        private helper: HelperService
    ) { }

    api = this.helper.server+'feed/get/block';
    key = this.helper.getCustomCredentials(20);

    // feed/get/block?websiteId=1&storeId=101&block=editorials&debug&find=blockId:editorials,id:102
    getMaterials = this.api+this.key+'&block=materials';
    singleMaterial = this.getMaterials+'&extend&find=title:';
    singleMaterialByUrlKey = this.getMaterials+'&extend&find=content.urlKey:'

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
    
    httpGetMaterial(material: string): Promise<any> {

        if(!!material) {
            return this.http.get(this.singleMaterial+material)
                .toPromise()
                .then(response => response.json().data.list)
                .catch(this.handleError);
        } else {
            return this.http.get(this.getMaterials)
                .toPromise()
                .then(response => response.json().data)
                .catch(this.handleError);
        }
    }

    getMaterialsByUrlKey(material: string): Promise<any> {
        return this.http.get(this.singleMaterialByUrlKey+material+'&wrapContent')
            .toPromise()
            .then(response => response.json().data)
            .catch(this.handleError)
    }
}