import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';

import {UserNotificationsRights} from './userNotificationsRights';
import {CustomOptions} from '../../openaireLibrary/services/servicesUtils/customOptions.class';
import {map} from "rxjs/operators";

@Injectable()
export class ManageUserNotificationsService {

    constructor(private http: HttpClient) {
    }

    getUserNotifications(properties: EnvProperties, pid: string, email: string) {
      let url: string = properties.adminToolsAPIURL + 'community/'+ pid + '/notifications';
        return this.http.get(url)//.map(res => <any> res.json())
                                 .pipe(map(res => this.parseUserNotifications(res, email)));
    }

    updateUserNotifications(properties: EnvProperties, pid: string, userNotificationsRights: any) {
        //let headers = new Headers({'Content-Type': 'application/json'});
        //let options = new RequestOptions({headers: headers});
        let body = JSON.stringify(userNotificationsRights);
        let url: string = properties.adminToolsAPIURL + 'community/' + pid + '/notifications';
        return this.http.post(url, body, CustomOptions.getAuthOptionsWithBody());
                        //.do(request => console.log("Insert Response:"+request.status));
    }

    parseUserNotifications(data:any, email:string): UserNotificationsRights {

        var notificationRights: UserNotificationsRights = new UserNotificationsRights();

        for (let i = 0; i < data.length; i++) {
            if (email == data[i].managerEmail) {
                notificationRights['notifyForNewManagers'] = data[i].notifyForNewManagers;
                notificationRights['notifyForNewSubscribers'] = data[i].notifyForNewSubscribers;
                notificationRights['managerEmail'] = data[i].managerEmail;
            }
        }
        return notificationRights;
    }
  }
