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

@Component({
  selector: 'app-nav-commercant',
  templateUrl: './nav-commercant.component.html',
  styleUrls: ['./nav-commercant.component.scss'],
  providers: [AuthService]
})
export class NavCommercantComponent implements OnInit {
  user: Observable<firebase.User>;
  commercant: Commercant;
  profileData: FirebaseListObservable<any[]>;
  role: any;
  nameCommercant: string;
  avatarCommercant: string;

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

    this.nameCommercant = '';
    this.avatarCommercant = '';
    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.commercant = element;
              if (this.commercant !== undefined) {
                this.nameCommercant = this.commercant.commercialName;
                this.avatarCommercant = this.commercant.image.downloadURL;
              }
            });
          });
        }
      }
    );

  }

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

  ngOnInit() {
  }


}

