import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { AngularFireDatabase } from 'angularfire2/database';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';

import { User } from '../../../models/User';
import { Parrain } from '../../../models/Parrain';
import { Commercant } from '../../../models/Commercant';
import { FireImg } from '../../../models/FireImg';
import { AuthService } from '../../services/auth/auth.service';

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [AuthService]
})
export class LoginComponent implements OnInit, OnDestroy {
  email: string;
  password: string;
  myUser: User;
  parrain: Parrain;
  commercant: Commercant;
  echecLogin: boolean;
  echecLoginEmailNotVerifed: boolean;
  user: Observable<firebase.User>;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private authService: AuthService) {
    this.echecLogin = false;
    this.echecLoginEmailNotVerifed = false;
    this.user = afAuth.authState;
    this.email = '';
    this.password = '';
    this.myUser = new User();
  }
  keyDownFunction(event) {
    if (event.keyCode === 13) {
      // rest of your code
      if (this.email !== '' && this.password !== '') {
        this.login();
      }
    }
  }
  login() {
    try {
      this.authService.signIn(this.email, this.password).catch(e => {
        this.echecLogin = true;
        this.echecLoginEmailNotVerifed = false;
      });
      this.user.subscribe(
        (auth) => {
          if(auth){
            if(auth.emailVerified === false){
              this.echecLogin = false;
              this.echecLoginEmailNotVerifed = true;
            }
          }
        });
    }catch (e) {
      console.log(e);
    }
  }


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


  ngOnInit() {
    // firebase.auth().signOut();
    /*try {
      this.user.subscribe(
        (auth) => {
          if (auth.email !== this.email) {
            this.router.navigate(['/']);
          } else {
            console.log('aucun user connecté');
          }
        });
    } catch (e) {
      // No content response..
      console.log(e);
      console.log('aucun user connecté');
    }*/
  }

  ngOnDestroy() {
    this.email = '';
    this.password = '';
    this.myUser = {
      uid: '',
      image: new FireImg(),
      email: '',
      emailVerified: false,
      password: '',
      status: ''
    };

  }
}
