import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs';
import {COOKIE} from "../../openaireLibrary/login/utils/helper.class"
import { HtmlPageContent } from "../../domain/html-page-content";
import { CustomOptions } from '../../openaireLibrary/services/servicesUtils/customOptions.class';
import {catchError} from "rxjs/operators";

@Injectable()
export class HtmlPageContentService {

    constructor(private http:HttpClient) {
    }

    static removeNulls(obj){
        var isArray = obj instanceof Array;
        for (var k in obj){
            if (obj[k]===null || obj[k]==='') isArray ? obj.splice(k,1) : delete obj[k];
            else if (typeof obj[k]=="object") HtmlPageContentService.removeNulls(obj[k]);
        }
    }

      getHtmlPageContent(community : string, page: string, adminToolsAPIURL:string) {
          return this.http.get<Array<HtmlPageContent>>(adminToolsAPIURL + 'htmlpagecontent?community=' + community + "&page="+page)
              //.map(res => <HtmlPageContent> res.json())
              .pipe(catchError(this.handleError));
      }

      updateHtmlPageContent(htmlPageContent: HtmlPageContent, adminToolsAPIURL:string) {
          //let headers = new Headers({'Content-Type': 'application/json'});
          //let options = new RequestOptions({headers: headers});

          HtmlPageContentService.removeNulls(htmlPageContent);

          return this.http.post<HtmlPageContent>(adminToolsAPIURL + 'htmlpagecontent/update', JSON.stringify(htmlPageContent), CustomOptions.getAuthOptionsWithBody())
          //return this.http.post(adminToolsAPIURL + 'htmlpagecontent/update', JSON.stringify(htmlPageContent), options)
              //.map(res => <HtmlPageContent> res.json())
              .pipe(catchError(this.handleError));
      }

      private handleError(error: HttpErrorResponse) {
          // in a real world app, we may send the error to some remote logging infrastructure
          // instead of just logging it to the console
          console.error(error);
          return Observable.throw(error.error || 'Server error');
      }

}
