import { Component, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { AuthenticationDto } from 'src/app/_dto/authentication.dto';
import { routePath } from 'src/app/_providers/_resources/route-path.properties';
import { AuthService } from 'src/app/_providers/_services/auth.service';
import { ErrorTranslateService } from 'src/app/_providers/_services/error-translate.service';
import { UiService } from 'src/app/_providers/_services/ui.service';

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

  user: AuthenticationDto = new AuthenticationDto();
  loginForm: UntypedFormGroup;
  loading = false;
  submitted = false;
  returnUrl: string;
  error = '';
  id: string;
  img: string;



  constructor(
    private service: AuthService,
    private formBuilder: UntypedFormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private _ui: UiService,
    private errorTranslateService: ErrorTranslateService,
    private _activeRouter: ActivatedRoute
  ) { }

  ngOnInit() {
    this._activeRouter.paramMap.subscribe(async (param: ParamMap) => {
      if (param.get('id')) {
        this.id = param.get('id');
        localStorage.setItem('institute', this.id)
        this.img = "../../../../assets/accurate/images/" + this.id + ".png"
      }

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

    // get return url from route parameters or default to '/'
  //   this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  //   localStorage.setItem('returnUrl',this.returnUrl)
  // }
  this.route.queryParams.subscribe(params => {
    
    this.returnUrl = params['returnUrl'] ;
    
});
  }
  // openSnackBar(message: string, action: string) {
  //   this._snackBar.open(message, action);
  // }


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

  preSave() {
    if (!this.user.username || this.user.username == null) {
      this._ui.toastMessage(this.errorTranslateService.translate("userNameCantbeBlank"));
      return false;
    }
    if (!this.user.password || this.user.password == null) {
      this._ui.toastMessage(this.errorTranslateService.translate("passwordCantbeBlank"));
      return false;
    }
    return true;
  }
  goToHome(){
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#hero';
  }
  goToContactUs(){
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#contact';
  }


  onSubmit() {
    if (!this.preSave())
      return
    this.loading = true; 
    this.error = "";
    this.submitted = true;
     
    if (this.loginForm.invalid) {
      this.loading = false; 
      return;
    }

    this.service.signIn(this.user)
      .then(async (res: any) => {
        // localStorage.setItem('seculevel', res.seculevel);
        localStorage.setItem('authtoken', res.accessToken);
        localStorage.setItem('refreshtoken', res.refreshToken);
        localStorage.setItem('emailId', res.emailId);
       
     

        await this._ui.getUserInfo({ username: this.user.username }).then((res) => {
          
          
          localStorage.setItem('username', res.username);
          localStorage.setItem('userId', res.userId);
          localStorage.setItem('mobile', res.mobile);
          localStorage.setItem('seculevel', res.secuLevel);
         
          
          if(res.secuLevel && res.secuLevel=='Admin'){
            this.router.navigate([routePath.admin]);
          }
          if(res.secuLevel && res.secuLevel=='SuperAdmin'){
            this.router.navigate([routePath.superAdmin]);
          }
          if(res.secuLevel && res.secuLevel=='Analyst'){
            this.router.navigate([routePath.analyst]);
          }
          if(res.secuLevel && res.secuLevel=='User'){
            this.router.navigate([routePath.user]);
          }
        }, (err) => { 
          this._ui.toastMessage((err.error.message) ? err.error.message : this.errorTranslateService.translate('errorInApi'));
        });
        
        
        if(this.returnUrl){
          this.router.navigate([this.returnUrl]);
          localStorage.removeItem('returnUrl')
        }
        else{
           
        this.user.password = '';
        this.error = '';
      }
      }, (err) => {
        this.loading = false; 
        localStorage.setItem('authtoken', '');
        localStorage.setItem('refreshtoken', '');
        localStorage.setItem('emailId', '');
        localStorage.removeItem('authtoken');
        localStorage.removeItem('refreshtoken');
        localStorage.removeItem('media');
        localStorage.removeItem('emailId');
        localStorage.removeItem('passwordVersion');
        
        if (err.status == 0) {
          this.error = "* Failed to load Database";
          this.loading = false;
          setTimeout(() => {
            this.error = ''
          }, 3000);
        } else if (err.status == 422) {
          this.error = "* Not Registered";
          this.loading = false;
          setTimeout(() => {
            this.error = ''
          }, 3000);
        }
        else if (err.status == 500) {
          this.error = "* Invalid Credentials";
          this.loading = false;
          setTimeout(() => {
            this.error = ''
          }, 3000);
        }
        else if (err.status == 400) {
          this.error = err.error.message;
          this.loading = false;
          setTimeout(() => {
            this.error = ''
          }, 3000);
        }
        else if (err.status == 401) {
          this.error = err.error.message;
          this.loading = false;
          setTimeout(() => {
            this.error = ''
          }, 3000);
        }
        else {
          // if (isArray(err.error.message)) {
          //   const error = err.error.message[0].constraints;
          //   if (error?.minLength)
          //     this.error = '* ' + error.minLength;
          //   this.loading = false;
          // } else {
          //   this.error = '* ' + err.error.message;
          //   this.loading = false;
          // }
        }
        this._ui.toastMessage(this.error, 2000);
      });

  }

  async goToRegister() {
    await this.router.navigate(["auth/register"]);
  }

  async goToForgotPassword() {
    await this.router.navigate(["auth/reset-password"], { queryParams: {school:this.id} });
  }
}
