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 { Parrain } from '../../../../models/Parrain';
import { Router } from '@angular/router';

@Component({
  selector: 'app-nav-parrain',
  templateUrl: './nav-parrain.component.html',
  styleUrls: ['./nav-parrain.component.scss'],
  providers: [AuthService]
})
export class NavParrainComponent implements OnInit {

  user: Observable<firebase.User>;
  parrain: Parrain;
  profileData: FirebaseListObservable<any[]>;
  role: any;
  nameParrain: string;
  avatarParrain: string;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private authService: AuthService) {

    this.nameParrain = '';
    this.avatarParrain = '';
    this.user = afAuth.authState;
    this.user.subscribe(
      (auth) => {
        if (auth) {
          this.profileData = this.afDb.list('/' + auth.displayName + '/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid.toString()
              }
            }
          );
          this.profileData.forEach(utilisateur => {
            utilisateur.forEach(element => {
              this.parrain = element;
              if (this.parrain !== undefined) {
                this.nameParrain = this.parrain.firstname;
                this.avatarParrain = this.parrain.image.downloadURL;
              }
            });
          });
        }
      }
    );

  }

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

  ngOnInit() {
  }

}
