import {Inject, Injectable, Output, ViewContainerRef} from '@angular/core';
import * as firebase from 'firebase';
import 'rxjs/add/operator/take';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {AuthService} from './auth.service';
import {User} from '../components/user/users/users.service';
import {GlobalService} from './global.service';
import {Dialog} from './dialog';
import {Toast, ToasterService} from 'angular5-toaster/dist';
import {AngularFireDatabase} from '@angular/fire/database';
import {AngularFireAuth} from '@angular/fire/auth';

@Injectable()
export class MessagingService {
    user: User;
    test;
    messaging = firebase.messaging();

    currentMessage = new BehaviorSubject(null);


    constructor(private db: AngularFireDatabase,
                private afAuth: AngularFireAuth,
                private authService: AuthService,
                private global: GlobalService,
                private dialog: Dialog,
                private toastService: ToasterService,
    ) {

    }
    updateToken(token) {
        // inja ma token firebase ro migirim
        this.afAuth.authState.take(1).subscribe(user => {
            if (!user) {
                return;
            }
            const data = {[user.uid]: token};
            this.db.object('fcmTokens/').update(data);
        });
    }

    getPermission() {
        this.messaging.requestPermission()
            .then(() => {
                return this.messaging.getToken();
            })
            .then(token => {
                this.authService.cloud_token.next(token);
                this.updateToken(token);

            })
            .catch((err) => {
                console.log('Unable to get permission to notify.', err);
            });
    }

    receiveMessage() {
        // todo tabe update request ro inja bezar
        this.messaging.onMessage((payload) => {
            let notification = JSON.parse(payload['data']['notification']);
            let toast: Toast = {
                type: 'info',
                title: notification['title'],
                // body: ToasterButtonComponent,
                // bodyOutputType: BodyOutputType.Component,
                //data: payload,
            };
            this.toastService.pop(toast);
            //this.currentMessage.next(payload);
        });
    }
}
