/**
 * Created by stefania on 7/13/17.
 */
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Page } from "../domain/page";
import { PageHelpContent } from "../domain/page-help-content";
import { Community } from "../domain/community";
import { Entity } from "../domain/entity";
import { DivId } from "../domain/divId";
import { DivHelpContent } from "../domain/div-help-content";
import {COOKIE} from "../openaireLibrary/login/utils/helper.class"

import {CommunityStatistics} from "../domain/statistics-classes";

@Injectable()
export class HelpContentService {

    constructor(private http:Http) {
    }

    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") HelpContentService.removeNulls(obj[k]);
        }
    }

    getDivIdsFull(community_pid: string, page_id: string, helpContentUrl:string) {
      if(page_id) {
        return this.http.get(helpContentUrl + 'divFull?community='+community_pid+'&page='+page_id)
            .map(res => <Array<DivId>> res.json())
            .catch(this.handleError);
      } else {
        return this.http.get(helpContentUrl + 'divFull?community='+community_pid)
            .map(res => <Array<DivId>> res.json())
            .catch(this.handleError);
      }
    }

    updateDivId(divId: DivId, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(divId);

        return this.http.post(helpContentUrl + 'div/update', JSON.stringify(divId), options)
            .map(res => <DivId> res.json())
            .catch(this.handleError);
    }

    getDivId(divId: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'div/'+divId)
            .map(res => <DivId> res.json())
            .catch(this.handleError);
    }

    saveDivId(divId: DivId, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(divId);

        return this.http.post(helpContentUrl + 'div/save', JSON.stringify(divId), options)
            .map(res => <DivId> res.json())
            .catch(this.handleError);
    }

    getCommunitiesWithDivId(helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'community?div=true')
            .map(res => <Array<Community>> res.json())
            .catch(this.handleError);
    }

    getCommunityPagesWithDivId(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'community/'+community_pid+'/pages?div=true')
            .map(res => <Array<Page>> res.json())
            .catch(this.handleError);
    }

    getCommunityDivHelpContents(community_pid: string, helpContentUrl:string) {
      return this.http.get(helpContentUrl + 'divhelpcontent?community='+community_pid)
          .map(res => <Array<DivHelpContent>> res.json())
          .catch(this.handleError);
    }

    getDivHelpContent(id : string, helpContentUrl:string) {
      return this.http.get(helpContentUrl + 'divhelpcontent/' + id)
          .map(res => <DivHelpContent> res.json())
          .catch(this.handleError);
    }

    insertOrUpdateDivHelpContent(divHelpContent: DivHelpContent, helpContentUrl:string) {

        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(divHelpContent);

        return this.http.post(helpContentUrl + 'divhelpcontent', JSON.stringify(divHelpContent), options)
            .map(res => <DivHelpContent> res.json())
            .catch(this.handleError);
    }

    deleteDivIds(ids : string[], helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'div/delete',JSON.stringify(ids), options)
            .catch(this.handleError);
    }

    deleteDivHelpContents(ids : string[], helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'divhelpcontent/delete',JSON.stringify(ids), options)
            .catch(this.handleError);
    }

    toggleDivHelpContents(ids : string[],status : boolean, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'divhelpcontent/toggle?status='+ status.toString(), JSON.stringify(ids), options)
            //.map( res => <string[]> res.json())
            .catch(this.handleError);
    }

    getPagesWithDivIds(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'div/pages?communtity='+community_pid)
            .map(res => <Map<string, Set<string>>> res.json())
            .catch(this.handleError);
    }

    getPages(helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'page')
            .map(res => <Array<Page>> res.json())
            .catch(this.handleError);
    }

    getPage(pageId:string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'page/'+pageId)
            .map(res => <Page> res.json())
            .catch(this.handleError);
    }

    getCommunities( helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'community')
            .map(res => <Array<Community>> res.json())
            .catch(this.handleError);
    }

    getCommunity(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'community/'+community_pid)
            .map(res => <Community> res.json())
            .catch(this.handleError);
    }

    getCommunitiesFull( helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'communityFull')
            .map(res => <Array<Community>> res.json())
            .catch(this.handleError);
    }

    getCommunityFull(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'communityFull/'+community_pid)
            .map(res => <Community> res.json())
            .catch(this.handleError);
    }

    saveCommunity(community: Community, helpContentUrl:string) {
        // let headers = new Headers({'Content-Type': 'application/json'});
        // let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(community);

        return this.http.post(helpContentUrl + 'community/save', JSON.stringify(community), this.getAuthOptionsWithBody())
            .map(res => <Community> res.json())
            .catch(this.handleError);
    }

    updateCommunity(community: Community, helpContentUrl:string) {
        // let headers = new Headers({'Content-Type': 'application/json'});
        // let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(community);

        return this.http.post(helpContentUrl + 'community/update', JSON.stringify(community),  this.getAuthOptionsWithBody())
            .map(res => <Community> res.json())
            .catch(this.handleError);
    }

    deleteCommunities(ids : string[], helpContentUrl:string) {
        // let headers = new Headers({'Content-Type': 'application/json'});
        // let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'community/delete',JSON.stringify(ids), this.getAuthOptionsWithBody())
            .catch(this.handleError);
    }

    getCommunityPages(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'community/'+community_pid+'/pages')
            .map(res => <Array<Page>> res.json())
            .catch(this.handleError);
    }

    getCommunityPagesByType(community_pid: string, params: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'community/'+community_pid+'/pages'+params)
            .map(res => <Array<Page>> res.json())
            .catch(this.handleError);
    }

    getEntities(helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'entity')
            .map(res => <Array<Entity>> res.json())
            .catch(this.handleError);
    }

    getCommunityEntities(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'community/'+community_pid+'/entities')
            .map(res => <Array<Entity>> res.json())
            .catch(this.handleError);
    }


    saveEntity(entity: Entity, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(entity);

        return this.http.post(helpContentUrl + 'entity/save', JSON.stringify(entity), options)
            .map(res => <Entity> res.json())
            .catch(this.handleError);
    }

    updateEntity(entity: Entity, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(entity);

        return this.http.post(helpContentUrl + 'entity/update', JSON.stringify(entity), options)
            .map(res => <Entity> res.json())
            .catch(this.handleError);
    }

    // toggleEntity(selectedCommunityId: string, id : string,status : boolean) {
    //     let headers = new Headers({'Content-Type': 'application/json'});
    //     let options = new RequestOptions({headers: headers});
    //
    //     return this.http.post(helpContentUrl + 'community/'+selectedCommunityId+'/entity/toggle?status='+ status.toString()+'&entityId='+id.toString(), options)
    //         .catch(this.handleError);
    // }

    toggleEntities(selectedCommunityPid: string, ids : string[],status : boolean, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl +'community/'+selectedCommunityPid+ '/entity/toggle?status='+ status.toString(), JSON.stringify(ids), options)
            //.map( res => <string[]> res.json())
            .catch(this.handleError);
    }

    deleteEntities(ids : string[], helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'entity/delete',JSON.stringify(ids), options)
            .catch(this.handleError);
    }


    toggleEntityOfPage(pageId: string, entityId : string,status : boolean, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'page/'+pageId+'/entity/toggle?status='+ status.toString()+'&entityId='+entityId.toString(), options)
            .catch(this.handleError);
    }

    savePage(page: Page, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(page);

        return this.http.post(helpContentUrl + 'page/save', JSON.stringify(page), options)
            .map(res => <Page> res.json())
            .catch(this.handleError);
    }

    updatePage(page: Page, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(page);

        return this.http.post(helpContentUrl + 'page/update', JSON.stringify(page), options)
            .map(res => <Page> res.json())
            .catch(this.handleError);
    }

    togglePages(selectedCommunityPid: string, ids : string[],status : boolean, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'community/'+selectedCommunityPid+'/page/toggle?status='+ status.toString(),JSON.stringify(ids), options)
            .catch(this.handleError);
    }

    deletePages(ids : string[], helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'page/delete',JSON.stringify(ids), options)
            .catch(this.handleError);
    }

    getPageHelpContents(helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'pagehelpcontent')
            .map(res => <Array<PageHelpContent>> res.json())
            .catch(this.handleError);
    }

    getCommunityPageHelpContents(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'pagehelpcontent?community='+community_pid)
            .map(res => <Array<PageHelpContent>> res.json())
            .catch(this.handleError);
    }

    getPageHelpContent(id : string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'pagehelpcontent/' + id)
            .map(res => <PageHelpContent> res.json())
            .catch(this.handleError);
    }

    savePageHelpContent(pageHelpContent: PageHelpContent, helpContentUrl:string) {

        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(pageHelpContent);

        return this.http.post(helpContentUrl + 'pagehelpcontent/save', JSON.stringify(pageHelpContent), options)
            .map(res => <PageHelpContent> res.json())
            .catch(this.handleError);
    }

    updatePageHelpContent(pageHelpContent: PageHelpContent, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        HelpContentService.removeNulls(pageHelpContent);

        return this.http.post(helpContentUrl + 'pagehelpcontent/update', JSON.stringify(pageHelpContent), options)
            .map(res => <PageHelpContent> res.json())
            .catch(this.handleError);
    }

    deletePageHelpContents(ids : string[], helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'pagehelpcontent/delete',JSON.stringify(ids), options)
            .catch(this.handleError);
    }

    togglePageHelpContents(ids : string[],status : boolean, helpContentUrl:string) {
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this.http.post(helpContentUrl + 'pagehelpcontent/toggle?status='+ status.toString(), JSON.stringify(ids), options)
            //.map( res => <string[]> res.json())
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        // 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.json().error || 'Server error');
    }
    public getAuthOptionsWithBody():RequestOptions{
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('X-XSRF-TOKEN',  COOKIE.getCookie(COOKIE.cookieName_id));
    let options = new RequestOptions({ headers: headers, withCredentials:true  });
      return options;
    }

    getDataProviders() {
        return this.http.get('https://beta.services.openaire.eu/search/v2/api/datasources?format=json').map(res => <any> res.json()).map(res => res.results).do(res => {console.log(res)}).catch(this.handleError);
    }

    getStatistics(community_pid: string, helpContentUrl:string) {
        return this.http.get(helpContentUrl + 'statistics/'+community_pid)
            .map(res => <CommunityStatistics> res.json())
            .catch(this.handleError);
    }

}
