import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { AuthService } from '../../../services/auth/auth.service';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { Admin } from '../../../../models/Admin';


@Component({
  selector: 'app-nav-admin',
  templateUrl: './nav-admin.component.html',
  styleUrls: ['./nav-admin.component.scss']
})
export class NavAdminComponent implements OnInit {
  user: Observable<firebase.User>;
  profileData: FirebaseListObservable<any[]>;
  role: any;
  adminData: FirebaseListObservable<any[]>;
  admin: Admin;
  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private authService: AuthService) {
    this.user = afAuth.authState;
    this.admin = new Admin();
    this.user.subscribe(
      (auth) => {
        if (auth) {
          this.adminData = this.afDb.list('/Admin/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid
              }
            }
          );
          this.adminData.forEach(avantage => {
            avantage.forEach(elementavantage => {
              this.admin = elementavantage;
              console.log(this.admin.email);
            });
          });
          this.profileData = this.afDb.list('/' + auth.displayName + '/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid.toString()
              }
            }
          );
        }
      }
    );
  }

  logout() {
    firebase.auth().signOut();
    this.authService.logout();
    this.user = null;
    this.router.navigate(['/']);
  }

  ngOnInit() {
  }

}
