import { Component, OnInit, ViewChild, HostListener } from "@angular/core";
import { AuthServiceService } from "src/app/shared/auth-service.service";
import { Router, ActivatedRoute } from "@angular/router";

import { Location } from '@angular/common';
import { NgxSpinnerService } from "ngx-spinner";
import { ToastrService } from "ngx-toastr";
import { NgForm } from "@angular/forms";
import { Response } from '@angular/http';



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

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

  @ViewChild('f') loginFormData: NgForm;

  screenHeight:any;
  saveDisabled: boolean = false;

  @HostListener('window:resize', ['$event'])
  getScreenSize(event?) {
        this.screenHeight = window.innerHeight;
        console.log(this.screenHeight);
  }

  

  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();
    
  }

  registerFun() {
    this.router.navigate(['../register'], {relativeTo: this.route});
  }
  forgetPassword(){
    this.router.navigate(['../forgetPassword'], {relativeTo: this.route});
  }
  //login function from services
  onSubmitedForm(){
    console.log(this.loginFormData.value);
    const dataForm = this.loginFormData.value;
    this.saveDisabled = true;

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



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