import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';

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 { OpCommercialService } from '../../../services/opCommercial/op-commercial.service';
import { Commercant } from '../../../../models/Commercant';

@Component({
  selector: 'app-carte-envoyer',
  templateUrl: './carte-envoyer.component.html',
  styleUrls: ['./carte-envoyer.component.scss'],
  providers: [AuthService, OpCommercialService]
})
export class CarteEnvoyerComponent implements OnInit {
  user: Observable<firebase.User>;
  carteParData: FirebaseListObservable<any[]>;
  profileData: FirebaseListObservable<any[]>;
  commercant: Commercant;
  show: boolean = false;
  i: number;
  hideme = {};
  databaseRef: any;
  statutAffiche: string;
  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router) {
    this.hideme = {}; // init is required
    this.statutAffiche = 'Toutes';
    this.databaseRef = firebase.database().ref();
    this.user = afAuth.authState;
    this.commercant = new Commercant();
    this.user.subscribe(
      (auth) => {

        if (auth) {
          this.carteParData = this.afDb.list('/CarteParrainage/', {
              query: {
                orderByChild: 'commercantCarte/uid',
                equalTo: auth.uid.toString()
              }
            }
          ).map((array) => array.reverse()) as FirebaseListObservable<any[]>;;

          this.profileData = this.afDb.list('/' + auth.displayName + '/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid.toString()
              }
            }
          );
          this.profileData.forEach(utilisateur => {
            utilisateur.forEach(element => {
              this.commercant = element;
            });
          });
        }
      }
    );
  }

  activeCarte(afficheStatus: string) {
    this.statutAffiche = afficheStatus;
  }

  ngOnInit() {
    try {
      this.user.subscribe(
        (auth) => {
          if (auth) {
            console.log(auth.uid);
          } else {
            // this.router.navigate(['/']);
          }
        });
    } catch (e) {
      // No content response..
      console.log(e);
      // this.router.navigate(['/']);
    }
  }

}
