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 { FormsModule }   from '@angular/forms';
import { LoginService } from '../../services/login/login.service';
import { User } from '../../../User';
import {forEach} from "@angular/router/src/utils/collection";

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [LoginService]
})
export class LoginComponent implements OnInit {
  user: Observable<firebase.User>;
  currentUser: Observable<User>;
  email: string;
  password: string;
  myUser: User;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase, private loginService: LoginService, private router: Router) {

    this.user = afAuth.authState;
    this.email = '';
    this.password = '';
    // console.log(this.afDb.database.ref().child('users/' + this.userId).orderByValue());
    /*
    this.afAuth.authState.subscribe(
      (auth) => {
        if(auth != null){
          this.myUser = this.afDb.object('users/' + auth.uid);
        }
      }
    )*/
  }

  login() {

    this.afAuth.auth.signInWithEmailAndPassword(this.email, this.password);
    this.user.subscribe(
      (auth) => {
        if (auth == null) {
        } else {
          /*
          const marequete = this.afDb.object('/users' + auth.uid);

          marequete.subscribe(utilisateur => {
            console.log('juste utilisateur: ' + utilisateur.firstname);
          });
          */
          const queryUs = this.afDb.list('/users', {
            query: {
              orderByChild: '_id',
              equalTo: auth.uid
            }
          });
          queryUs.subscribe(queriedUsers => {
            for (var i = 0; i < queriedUsers.length ; i++){
              if (queriedUsers[i]._id === auth.uid){
                console.log('its good ! ' + queriedUsers[i]._id + ' et ' + auth.uid);
                this.myUser = queriedUsers[i];
              }else{
                console.log('id sont diferrent dans login ! voicie auth.id : ' + auth.uid);
                console.log('queriedUsers[i]._id: ' + queriedUsers[i]._id);
              }
              console.log(queriedUsers[i].familyname);
              console.log(queriedUsers[i]._id);
            }
            // console.log(queriedUsers[0].familyname);
            // console.log(auth.uid);
            // this.myUser = queriedUsers[0];
          });
        }
      }
    );
    // console.log(typeof this.afDb.database.ref().child('users/').child(this.userId));
  }

  logout() {
    this.loginService.logout().then(userLogged => {
      console.log('logout');
      /*this.myUser = {
        _id: '',
        email: '',
        emailVerified: false,
        password: '',
        familyname: '',
        firstname: '',
        username: '',
        birthday: new Date(),
        idCard: '',
        secretCode: '',
        status: ''
      };*/
    });
  }

  loadHomeComponent() {
    this.router.navigate(['/']);
  }

  loadRegisterComponent() {
    this.router.navigate(['/register']);
  }

  ngOnInit() {
    this.myUser = {
      _id: '',
      email: '',
      emailVerified: false,
      password: '',
      familyname: '',
      firstname: '',
      username: '',
      birthday: new Date(),
      idCard: '',
      secretCode: '',
      status: ''
    };
  }

}
