import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import * as firebase from 'firebase/app';
import { AuthService } from '../../../services/auth/auth.service';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Component({
  selector: 'app-reset-password',
  templateUrl: './reset-password.component.html',
  styleUrls: ['./reset-password.component.scss'],
  providers: [AuthService]
})
export class ResetPasswordComponent implements OnInit, OnDestroy {
  email: string;
  emailExist: boolean;
  profileDataParrainEmail: FirebaseListObservable<any[]>;
  profileDataCommercantEmail: FirebaseListObservable<any[]>;

  constructor(private router: Router, private afDb: AngularFireDatabase) {
    this.email = '';
  }

  resetPass() {
    if (this.email !== '') {
      this.verifEmail(this.email);
    }
  }

  verifEmail(email: string){
    let parrainExistPas = false;
    let commercantExistPas = false;

    this.profileDataParrainEmail = this.afDb.list('/Parrain/', {
        query: {
          orderByChild: 'email',
          equalTo: email
        }
      }
    );
    this.profileDataParrainEmail.subscribe(snapshot => {
      if (snapshot.length > 0) {
        firebase.auth().sendPasswordResetEmail(email);
        this.emailExist =  true;
      } else {
        parrainExistPas = true;
      }
    });
    this.profileDataCommercantEmail = this.afDb.list('/Commercant/', {
        query: {
          orderByChild: 'email',
          equalTo: email
        }
      }
    );
    this.profileDataCommercantEmail.subscribe(snapshot => {

      if (snapshot.length > 0) {
        firebase.auth().sendPasswordResetEmail(email);
        this.emailExist =  true;
      } else {
        commercantExistPas = true;
        if (parrainExistPas && commercantExistPas) {
          this.emailExist =  false;
        }
      }
    });
  }
  loadHomeComponent() {
    this.router.navigate(['/']);
  }
  ngOnInit() {
  }
  ngOnDestroy() {
    this.email = '';
  }
}
