/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */

import {Injectable, EventEmitter} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Injectable()
export class NotificationsService {

    public emiter: EventEmitter<any> = new EventEmitter();

    constructor(private translate: TranslateService) {}
    set(notification: any, to: boolean) {
        this.translateNotification(notification);
        notification.id = notification.override && notification.override.id ? notification.override.id : Math.random().toString(36).substring(3);
        this.emiter.emit({command: "set", notification: notification, add: to});
        return notification;

    };
    getChangeEmitter() { return this.emiter }

    //// Access methods
    success(title: string, content: string, override?: any) { return this.set({title: title, content: content, type: "success", override: override}, true) }
    error(title: string, content: string, details?: string, override?: any) { return this.set({title: title, content: content, type: "error", override: override, details: details}, true) }
    alert(title: string, content: string, override?: any) { return this.set({title: title, content: content, type: "alert", override: override}, true) }
    info(title: string, content: string, override?: any) { return this.set({title: title, content: content, type: "info", override: override}, true) }
    warning(title: string, content: string, override?: any) { return this.set({title: title, content: content, type: "warning", override: override}, true) }

    // With type method
    create(title: string, content: string, type: string, override?: any) { return this.set({title: title, content: content, type: type, override: override}, true) }

    // HTML Notification method
    html(html: any, type: string, override?: any) { return this.set({html: html, type: type, override: override, title: null, content: null}, true) }

    // Remove all notifications method
    remove(id?: string) {
        if (id) this.emiter.emit({command: "clean", id: id});
        else this.emiter.emit({command: "cleanAll"});
    }

    translateNotification(notification: any) {
        if (notification.hasOwnProperty('title'))
            this.translate.get(notification.title).subscribe((res: string) => {
                notification.title = typeof res === 'string' ? res : notification.title;
            });
        if (notification.hasOwnProperty('content'))
            this.translate.get(notification.content).subscribe((res: string) => {
                notification.content = typeof res === 'string' ? res : notification.content;
            });
        if (notification.hasOwnProperty('html'))
            this.translate.get(notification.html).subscribe((res: string) => {
                notification.html = res;
            });
    }
}
