/**
 * Created by stefania on 7/13/17.
 */
import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders} from "@angular/common/http";
import { Observable } from 'rxjs';
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 {StatisticsDisplay, StatisticsSummary} from '../openaireLibrary/connect/statistics/statisticsEntities';
import { CustomOptions } from '../openaireLibrary/services/servicesUtils/customOptions.class';
import {catchError, map} from "rxjs/operators";
import {COOKIE} from "../openaireLibrary/login/utils/helper.class";


@Injectable()
export class HelpContentService {

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

    getDivIdsFull(page_id: string, helpContentUrl:string, pid: string = null) {
      let parameters: string = "";
      if(page_id || pid) {
        parameters = "?";
        if(page_id) {
          parameters += "&page="+page_id;
        }
        if(pid) {
          parameters += "&communityId="+pid;
        }
      }

      return this.http.get<Array<DivId>>(helpContentUrl + 'divFull'+parameters)
          //.map(res => <Array<DivId>> res.json())
          .pipe(catchError(this.handleError));
    }

    updateDivId(divId: DivId, helpContentUrl:string) {
        HelpContentService.removeNulls(divId);

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

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

    getDivIdFull(divId: string, helpContentUrl:string) {
        return this.http.get<DivId>(helpContentUrl + 'divFull/'+divId)
            //.map(res => <DivId> res.json())
            .pipe(catchError(this.handleError));
    }

    saveDivId(divId: DivId, helpContentUrl:string) {
        HelpContentService.removeNulls(divId);

        return this.http.post<DivId>(helpContentUrl + 'div/save', JSON.stringify(divId), CustomOptions.getAuthOptionsWithBody())
            //.map(res => <DivId> res.json())
            .pipe(catchError(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<Array<Page>>(helpContentUrl + 'community/'+community_pid+'/pages?div=true')
            //.map(res => <Array<Page>> res.json())
            .pipe(catchError(this.handleError));
    }

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

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

    insertOrUpdateDivHelpContent(divHelpContent: DivHelpContent, helpContentUrl:string) {
        HelpContentService.removeNulls(divHelpContent);

        return this.http.post<DivHelpContent>(helpContentUrl + 'divhelpcontent', JSON.stringify(divHelpContent), CustomOptions.getAuthOptionsWithBody())
            //.map(res => <DivHelpContent> res.json())
            .pipe(catchError(this.handleError));
    }

    deleteDivIds(ids : string[], helpContentUrl:string) {
        return this.http.post(helpContentUrl + 'div/delete',JSON.stringify(ids), CustomOptions.getAuthOptionsWithBody())
            .pipe(catchError(this.handleError));
    }

    deleteDivHelpContents(ids : string[], helpContentUrl:string) {
         return this.http.post(helpContentUrl + 'divhelpcontent/delete',JSON.stringify(ids), CustomOptions.getAuthOptionsWithBody())
            .pipe(catchError(this.handleError));
    }

    toggleDivHelpContents(ids : string[],status : boolean, helpContentUrl:string) {

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

    getPagesWithDivIds(community_pid: string, helpContentUrl:string) {
        let parameters = (community_pid ? "?communityId="+community_pid : "");
        return this.http.get<Array<string>>(helpContentUrl + 'div/pages'+parameters)
            //.map(res => <Map<string, Set<string>>> res.json())
            .pipe(catchError(this.handleError));
    }

    getPages(helpContentUrl:string,pid:string,with_positions:boolean=null) {
        let parameters: string = "";
        if(pid || with_positions == true || with_positions == false) {
          parameters = "?";
          if(pid) {
            parameters += "&pid="+pid;
          }
          if(with_positions == true || with_positions == false) {
            parameters += "&with_positions="+with_positions;
          }
        }
        return this.http.get<Array<Page>>(helpContentUrl + 'page'+parameters)
            //.map(res => <Array<Page>> res.json())
            .pipe(catchError(this.handleError));
    }

    getPagesFull(helpContentUrl:string,pid:string) {
        return this.http.get<Array<Page>>(helpContentUrl + 'pageFull'+(pid?("?pid="+pid):""))
        //.map(res => <Array<Page>> res.json())
          .pipe(catchError(this.handleError));
    }

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

    getPageByRoute(route:string, helpContentUrl:string) {
      return this.http.get<Page>(helpContentUrl + 'page/?page_route='+route)
        .pipe(catchError(this.handleError));
    }

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

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

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

    getCommunityFull(community_pid: string, helpContentUrl:string) {
        return this.http.get<Community>(helpContentUrl + 'communityFull/'+community_pid)
            //.map(res => <Community> res.json())
            .pipe(catchError(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<Community>(helpContentUrl + 'community/save', JSON.stringify(community), CustomOptions.getAuthOptionsWithBody())
        //.map(res => <Community> res.json())
            .pipe(catchError(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<Community>(helpContentUrl + 'community/update', JSON.stringify(community),  CustomOptions.getAuthOptionsWithBody())
            //.map(res => <Community> res.json())
            .pipe(catchError(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), CustomOptions.getAuthOptionsWithBody())
            .pipe(catchError(this.handleError));
    }

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

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

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


    saveEntity(entity: Entity, helpContentUrl:string) {
        HelpContentService.removeNulls(entity);

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

    updateEntity(entity: Entity, helpContentUrl:string) {
        HelpContentService.removeNulls(entity);

        return this.http.post<Entity>(helpContentUrl + 'entity/update', JSON.stringify(entity), CustomOptions.getAuthOptionsWithBody())
            //.map(res => <Entity> res.json())
            .pipe(catchError(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) {

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

    deleteEntities(ids : string[], helpContentUrl:string) {
        return this.http.post(helpContentUrl + 'entity/delete',JSON.stringify(ids), CustomOptions.getAuthOptionsWithBody())
            .pipe(catchError(this.handleError));
    }


    toggleEntityOfPage(pageId: string, entityId : string,status : boolean, helpContentUrl:string) {
        return this.http.post(helpContentUrl + 'page/'+pageId+'/entity/toggle?status='+ status.toString()+'&entityId='+entityId.toString(), CustomOptions.getAuthOptionsWithBody())
            .pipe(catchError(this.handleError));
    }

    savePage(page: Page, helpContentUrl:string) {
         HelpContentService.removeNulls(page);

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

    updatePage(page: Page, helpContentUrl:string) {

        HelpContentService.removeNulls(page);

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

    togglePages(selectedCommunityPid: string, ids : string[],status : boolean, helpContentUrl:string) {

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

    deletePages(ids : string[], helpContentUrl:string) {

        return this.http.post(helpContentUrl + 'page/delete',JSON.stringify(ids), CustomOptions.getAuthOptionsWithBody())
            .pipe(catchError(this.handleError));
    }

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

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

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

    savePageHelpContent(pageHelpContent: PageHelpContent, helpContentUrl:string) {
        HelpContentService.removeNulls(pageHelpContent);

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

    updatePageHelpContent(pageHelpContent: PageHelpContent, helpContentUrl:string) {
        HelpContentService.removeNulls(pageHelpContent);

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

    deletePageHelpContents(ids : string[], helpContentUrl:string) {
          return this.http.post(helpContentUrl + 'pagehelpcontent/delete',JSON.stringify(ids), CustomOptions.getAuthOptionsWithBody())
              .pipe(catchError(this.handleError));
    }

    togglePageHelpContents(ids : string[],status : boolean, helpContentUrl:string) {
        return this.http.post(helpContentUrl + 'pagehelpcontent/toggle?status='+ status.toString(), JSON.stringify(ids), CustomOptions.getAuthOptionsWithBody())
            //.map( res => <string[]> 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');
    }

    // 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);
    // }

    getCommunityStatistics(apiUrl: string, communityId: string): Observable<StatisticsSummary> {
        const url = `${apiUrl}communities/${communityId}`;
        //console.log(`getting statistics summary from: ${url}`);
        return this.http.get(url)
            //.map(res => <any>res.json())
            .pipe(map(res => res['statistics']));
    }

    getCommunityAdminStatisticsChoices(apiUrl: string, communityId: string): Observable<StatisticsDisplay> {
        const url = `${apiUrl}statistics/${communityId}`;
        //console.log(`getting admin choices for statistics from: ${url}`);
        return this.http.get<StatisticsDisplay>(url)
            //.map(stats => <StatisticsDisplay>stats.json())
            .pipe(catchError(this.handleError));
    }

    postCommunityAdminStatisticsChoices(apiUrl: string,
                                        communityId: string,
                                        entity: string,
                                        chartsOrNumbers: string,
                                        title: string,
                                        status: boolean,
                                        monitor: boolean): Observable<any> {
        const url = `${apiUrl}statistics/${communityId}/${entity}/${chartsOrNumbers}?status=${status.toString()}&monitor=${monitor.toString()}`;
        //console.log(`getting admin choices for statistics from: ${url}`);

        return this.http.post(url, title, CustomOptions.getAuthOptionsWithBody())
            //.map(stats => <any>stats.json())
            .pipe(catchError(this.handleError));
    }

    statisticsIsActiveToggle(apiURL: string, id: string): Observable<boolean> {
        const url = apiURL + '/statistics/' + encodeURIComponent(id) + '/toggle';
        return this.http.post<boolean>(url, {}, CustomOptions.getAuthOptionsWithBody()).pipe(catchError(this.handleError));
    }
}
