///<reference path="../../../../node_modules/angularfire2/database/database.d.ts"/>
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 { RegisterService } from '../../services/register/register.service';

import { User } from '../../../User';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss'],
  providers: [RegisterService]
})
export class RegisterComponent implements OnInit {
  user: Observable<firebase.User>;

  currentUser: User;
  email: string;
  password: string;
  name: string;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase, private router: Router) {
    this.user = afAuth.authState;

    this.name = '';
    this.email = '';
    this.password = '';



  }
  register() {
    this.afAuth.auth.createUserWithEmailAndPassword(this.currentUser.email, this.currentUser.password)
      .then(function (userRecord) {



      });

    this.user.subscribe(
      (auth) => {
        if (auth != null) {
          console.log('apres create user: ' + auth.uid);

          this.currentUser._id = auth.uid;
          console.log('apres create user: current user : ' + this.currentUser._id);
          //this.writeUserData(auth.uid);
        }
      }
    );
  }

  writeUserData(UID) {
    console.log(UID);
    firebase.database().ref('users/' + UID).set(this.currentUser);
    //this.ngOnInit();
    // this.userId = firebase.auth().currentUser.uid;

  }
  /*
  register() {
    this.admin.auth().createUser({
      email: 'titi@caille.com',
      emailVerified: false,
      idCard: '11234567890',
      secretCode: '11234567890',
      password: 'caille',
      displayName: 'Don titi',
      //photoURL: 'http://www.example.com/12345678/photo.png',
      disabled: false
    })
      .then(function(userRecord) {
        // See the UserRecord reference doc for the contents of userRecord.
        console.log('Successfully created new user:', userRecord.uid);
      })
      .catch(function(error) {
        console.log('Error creating new user:', error);
      });
  }*/



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

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

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