import { Component, OnInit, TemplateRef } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LoginService } from './login.service';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { AuthService } from '../auth.service';
import { ToastrService } from 'ngx-toastr';
import { User } from '../masters/user/user';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from '../Shared/commondialog/commondialog.component';
import { loginSignalRService } from './login.signalR.service';
import { LocationStrategy } from '@angular/common';
import { CommonService } from '../Shared/commonservice';
import { NgxSpinnerService } from 'ngx-spinner';


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

  // private _hubConnection: HubConnectionBuilder;
  loginForm: FormGroup;
  forgotuserForm: FormGroup;
  loading = false;
  submitted = false;
  returnUrl: '/dashboard';
  error = '';
  postresult: boolean;
  returnurl = '';
  bsModalRef: BsModalRef;
  anio: number = new Date().getFullYear();
  constructor(
    public signalrservice: loginSignalRService,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private loginService: LoginService,
    private modalService: BsModalService,
    private toastr: ToastrService,
    private authService: AuthService,
    private dialogService: DialogService,
    private location: LocationStrategy,
    private commonService: CommonService,
    private SpinnerService: NgxSpinnerService
  ) {
    history.pushState(null, null, window.location.href);
    this.location.onPopState(() => {
      history.pushState(null, null, window.location.href);
    });
  }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      emailid: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });

    this.forgotuserForm = this.formBuilder.group({
      email: ['', [Validators.required, Validators.email]]

    });
    if (localStorage.getItem('userid') != null) {
      // localStorage.clear();
      // localStorage.removeItem("LoggedIn");

    }
    this.route.queryParams
      .subscribe(params => this.returnurl = params['returnUrl']);
    // reset login status
    // this.loginService.logout();

  }

  // convenience getter for easy access to form fields
  get f() { return this.loginForm.controls; }

  get fuser() { return this.forgotuserForm.controls; }

  openforgotuserModal(template: TemplateRef<any>, user?: User) {
    this.bsModalRef = this.modalService.show(template);

  }

  PostforgotUser(user: User) {

    if (this.fuser.email.value !== '') {
      this.SpinnerService.show();
      this.commonService.sendemail(this.fuser.email.value, 'forgotpassword').subscribe(res => {
        if (res.status === 200) {
          this.postresult = true;
          this.ngOnInit();
          this.SpinnerService.hide();
        }
        this.toastr.success('Email Sent successfully');
        this.doHide();
      },
        error => {
          this.toastr.error(error.error);
          this.postresult = false;
          this.SpinnerService.hide();
        });
    } else {
      this.toastr.error('Please Enter Email Id');
    }
  }

  // onSubmit(http: HttpClient) {

  //   this.submitted = true;
  //   console.log('login');
  //   // stop here if form is invalid
  //   if (this.loginForm.invalid) {
  //     return;
  //   }



  //   this.loginService.login(this.f.emailid.value, this.f.password.value, 0).subscribe((Login: any) => {

  //     this.authService.setSecureToken(Login.token);
  //     localStorage.setItem('userid', Login.userid);
  //     localStorage.setItem('username', Login.firstname);
  //     localStorage.setItem('emailid', this.f.emailid.value);
  //     localStorage.setItem('logid', Login.logid);

  //     this.signalrservice.createConnection();
  //     this.signalrservice.registerOnServerEvents();
  //     this.signalrservice.startConnection();

  //     // this.router.navigate(['/home']);
  //     if (this.returnurl !== '' && this.returnurl !== undefined) {
  //       this.router.navigateByUrl(this.returnurl);
  //     } else {
  //       this.router.navigate(['/dashboard']);
  //     }
  //   },

  //     (err: HttpErrorResponse) => {



  //       if (err.error === 'loggedin') {
  //         this.dialogService.addDialog(CommondialogComponent,
  //           {
  //             title: 'Please Confirm',
  //             message: 'Already you are logged in another location. Do you want Continue..?',
  //             hclass: 'modelsuccess',
  //             oktext: 'Yes',
  //             canceltext: 'No',
  //             okshow: true,
  //             cancelshow: true
  //           }).subscribe((isConfirmed) => {
  //             if (isConfirmed) {

  //               this.loginService.login(this.f.emailid.value, this.f.password.value, 1).subscribe((Login: any) => {

  //                 this.authService.setSecureToken(Login.token);
  //                 localStorage.setItem('userid', Login.userid);
  //                 localStorage.setItem('username', Login.firstname);
  //                 localStorage.setItem('logid', Login.logid);
  //                 localStorage.setItem('emailid', this.f.emailid.value);


  //                 this.signalrservice.createConnection();
  //                 this.signalrservice.registerOnServerEvents();
  //                 this.signalrservice.startConnection();




  //                 this.router.navigate(['/dashboard']);
  //               },
  //                 // tslint:disable-next-line: no-shadowed-variable
  //                 (err: HttpErrorResponse) => {
  //                   this.toastr.error(err.error);
  //                 });
  //             } else {
  //               location.reload();
  //             }
  //           });

  //       } else {
  //         this.toastr.error(err.error);
  //         this.loading = false;
  //       }
  //     });
  // }
  calllogin(){
    this.loginService.login(this.f.emailid.value, this.f.password.value, 1).subscribe((Login: any) => {
      this.authService.sessionSetItem(this.authService.LoggedIn, Login.token);
      this.authService.setSecureToken(Login.token);
      localStorage.setItem('userid', Login.userid);
      localStorage.setItem('username', Login.firstname);
      localStorage.setItem('logid', Login.logid);
      localStorage.setItem('emailid', this.f.emailid.value);
      localStorage.setItem('roleid', Login.roleid);
      localStorage.setItem('signoff_status','1');
      sessionStorage.setItem('sessionexpire', 'false');
      //localStorage.setItem('sessionexpire', 'false');

      this.signalrservice.createConnection();
      this.signalrservice.registerOnServerEvents();
      this.signalrservice.startConnection();
      if( Login.roleid == '38') {
          this.router.navigate(['/reports/vlexreport']);
      } else {        
          this.router.navigate(['/dashboard']);
      }    
    },
      // tslint:disable-next-line: no-shadowed-variable
      (err: HttpErrorResponse) => {
        this.toastr.error(err.error);
      });
  }
  onSubmit(http: HttpClient) {

    this.submitted = true;
    // stop here if form is invalid
    if (this.loginForm.invalid) {
      return;
    }
    if(localStorage.getItem("logid")){
      this.dialogService.addDialog(CommondialogComponent,
        {
          title: 'Please Confirm',
          message: 'Already you are logged in another location. Do you want Continue..?',
          hclass: 'modelsuccess',
          oktext: 'Yes',
          canceltext: 'No',
          okshow: true,
          cancelshow: true
        }).subscribe((isConfirmed) => {
          if (isConfirmed) {
            localStorage.clear();
            sessionStorage.clear();
            localStorage.removeItem('LoggedIn');
          this.calllogin();

          } else {
            //location.reload();
            //do nothing
          }
        });
    }else{
      this.loginService.login(this.f.emailid.value, this.f.password.value, 0).subscribe((Login: any) => {
        console.log('login',Login);
        if (Login.isrolemap) {
        this.authService.setSecureToken(Login.token);
        this.authService.sessionSetItem(this.authService.LoggedIn, Login.token);
        localStorage.setItem('userid', Login.userid);
        localStorage.setItem('username', Login.firstname);
        localStorage.setItem('emailid', this.f.emailid.value);
        localStorage.setItem('logid', Login.logid);    
        localStorage.setItem('roleid', Login.roleid);
        localStorage.setItem('signoff_status','1');
        localStorage.setItem('sessionexpire', 'false');
        this.signalrservice.createConnection();
        this.signalrservice.registerOnServerEvents();
        this.signalrservice.startConnection();
  
        // this.router.navigate(['/home']);
        if (this.returnurl !== '' && this.returnurl !== undefined) {
          this.router.navigateByUrl(this.returnurl);
        } else {
           if( Login.roleid == '38') {
              this.router.navigate(['/reports/vlexreport']);
            } else {        
              this.router.navigate(['/dashboard']);
            } 
        }
      } else {
        this.toastr.error('User is not mapped to any role. Please contact administrator');
      }
      },
  
        (err: HttpErrorResponse) => {
  
  
  
          if (err.error === 'loggedin') {
            this.dialogService.addDialog(CommondialogComponent,
              {
                title: 'Please Confirm',
                message: 'Already you are logged in another location. Do you want Continue..?',
                hclass: 'modelsuccess',
                oktext: 'Yes',
                canceltext: 'No',
                okshow: true,
                cancelshow: true
              }).subscribe((isConfirmed) => {
                if (isConfirmed) {
  
                  this.loginService.login(this.f.emailid.value, this.f.password.value, 1).subscribe((Login: any) => {
                    this.authService.sessionSetItem(this.authService.LoggedIn, Login.token);
                    this.authService.setSecureToken(Login.token);
                    localStorage.setItem('userid', Login.userid);
                    localStorage.setItem('username', Login.firstname);
                    localStorage.setItem('logid', Login.logid);
                    localStorage.setItem('emailid', this.f.emailid.value);
                    localStorage.setItem('roleid', Login.roleid);
                    localStorage.setItem('signoff_status','1');
                    localStorage.setItem('sessionexpire', 'false');
                    this.signalrservice.createConnection();
                    this.signalrservice.registerOnServerEvents();
                    this.signalrservice.startConnection();
                      if(Login.roleid == '38') {
                        this.router.navigate(['/reports/vlexreport']);
                      } else {        
                        this.router.navigate(['/dashboard']);
                      }                    
                    },
                    // tslint:disable-next-line: no-shadowed-variable
                    (err: HttpErrorResponse) => {
                      this.toastr.error(err.error);
                    });
                } else {
                  location.reload();
                }
              });
  
          } else {
            this.toastr.error(err.error);
            this.loading = false;
          }
        });
    }
  }
  doHide() {
    this.bsModalRef.hide();
  }
}
