import { Component, OnInit, ViewChild, Injectable, ChangeDetectorRef, AfterViewInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NbLoginComponent, NbAuthService } from '@nebular/auth';
import { NgForm } from '@angular/forms';
import { SharedService } from '../../shared/shared.service';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'ngx-login',
  templateUrl: './login.component.html',
})




export class NgxLoginComponent implements AfterViewInit {


  constructor(
    private auth: SharedService,
    private router: Router,
    private toster:ToastrService ) {
      if(!this.auth.isAuthenticated()) {
        router.navigate(['pages']);
      } else {
        router.navigate(['auth']);
      }
    }

  @ViewChild('f') loginForm: NgForm;
  @ViewChild('inputEmail') focusEmail;






  onSubmitedForm(){
    console.log(this.loginForm.value);
  
    //lgoin function 
  this.auth.onSignIn(this.loginForm.value)
    .subscribe(
      response => {
        console.log(response);
        localStorage.setItem('token', response['token']);
        console.log(this.auth.isAuthenticated());
        this.router.navigate(['pages']);
      },
      error => {
         console.log(error);
        this.toster.error('your email or password are not correct !');
        }
    );
  }
   

  ngAfterViewInit() {     
    this.focusEmail.nativeElement.focus();       
  }


}