import { Location } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthServiceService } from './../shared/auth-service.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Response } from '@angular/http';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private authSer: AuthServiceService, 
    private router: Router, 
    private route: ActivatedRoute, 
    private location: Location,
    private spinner: NgxSpinnerService,
    private toastr: ToastrService) { }

  @ViewChild('f') loginFormData: NgForm;

  myInnerHeight = window.innerHeight;

  

  ngOnInit() {
    if(!this.authSer.isAuthenticated()) {
      this.router.navigate(['ExternalPage']);
    }
    // this.authSer.showSearchHeader = false;
    this.authSer.notificationLogin = false;
    // this.authSer.showHeaderLogin = true;
    this.authSer.showHeaderDashBoard = false;
    this.authSer.showDashboardHeader = true;
    this.authSer.arabicTemplate = true;
    this.spinner.hide();
    
  }

  //login function from services
  onSubmitedForm(){
    console.log(this.loginFormData.value);
    const dataForm = this.loginFormData.value;
    this.authSer.login(dataForm).subscribe(
      (responce: Response) => {
        localStorage.setItem('token', responce['token']);
        localStorage.setItem('userType', responce['user'].type);
        const id = responce['user'].id;
        console.log(id);
        this.authSer.setDataUser(responce);
        this.loginFormData.reset();
        this.router.navigate(['/services/' + id]);
        // this.location.back();
      },
      (error) => {
        console.log(error);
        this.toastr.error( 'حدث خطأ' ,' تأكد من رقم الهويه او كلمه المرور ');
      }
    );
  }


  //pattern="^[1-9]+[0-9]*$"   => (number only)
}
