import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import {Http, Headers} from '@angular/http';
import {Router } from '@angular/router';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {
  submission: FirebaseListObservable<any>;
  constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase, private router: Router){
    console.log("Authentication service started");
    console.log(firebase.auth());

  }

  login(email, pass){
    this.afAuth.auth.signInWithEmailAndPassword(email, pass)
    .then(res => {
        console.log('Nice, logging you in!!!');
        this.router.navigate(['/admin']);
      });
  }

  checkAuth(){
    this.afAuth.authState.subscribe(res => {
      if (res && res.uid) {
        console.log('user is logged in');
        return true;
      } else {
        console.log('user not logged in...redirecting to welcome..');
        this.router.navigate(['/login']);
        return false;
      }
    });
  }

  logout() {
    this.afAuth.auth.signOut();
    this.router.navigate(['/']);
  }

}
