// Angular Core
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

// RxJs
import { catchError, Subscription, throwError } from 'rxjs';

// Components
import { CaptchaComponent } from 'src/app/components/captcha/captcha.component';

// Services
import { LoginService } from 'src/app/feature-modules/auth/services/login/login.service';
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';
import { SessionService } from 'src/app/services/session/session.service';
import { environment } from 'src/environments/environment';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';

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

  @ViewChild('captcha') captchaComponent!: CaptchaComponent;

  loginForm:any = FormGroup;
  submitted:boolean = false;
  showPassword: boolean = false;
  isSubmitted:boolean = false;
  imgUrl: string = environment.imageUrl;

  adminSession!: any;
  captchaInput!: string;

  /**
  * Default config object
  * @type Object
  */
  config: any = {
    userName:'',
    password:'',
    errorMessage:'',
    heading: 'ADMIN LOGIN',
    userNamePlaceholder: 'ENTER USERNAME',
    headingClass: 'admin-login-helptext',
    captchaRequired: true,
    forgotPassReqd: false,
    invalidFormMsg: 'Please Enter Username / Password',
    fromPage: 'adminLogin'
  };

  renderMe: boolean = false;
  authenticate: boolean = true;
  captcha!: string;
  currentYear: number = new Date().getFullYear();
  adminHomePage: string = "https://" + location.hostname + "/admin/index.php";

  /**
  * data to display in footer
  * @type Object
  */
 footerData = {
   year: this.currentYear,
   sitename: ''
 };


  constructor(
    private sessionService: SessionService,
    private loginService: LoginService,
    private formBuilder: FormBuilder,
    private localStorageService: LocalStorageService,
    private dataTransmitter: DataTransmitterService,
    private utilitiesService:UtilitiesService
  ) { }

  ngOnInit(): void {
    this.loginForm = this.formBuilder.group({
      userName: ['', Validators.required],
      password : ['', Validators.required],
      operation : [''],
      cnf_key : [''],
      redirect : [''],
      remember_username : [''],
      captchaInput: [''],
    });
    this.utilitiesService.updateLiveChat();
    this.getAdminSession();
  }

  getcaptchaInput(event:string){
    this.loginForm.patchValue({
      captchaInput: event,
    });
  }

  getcaptchaValue(event:string){
    this.captcha = event
  }

  get loginFormData() { return this.loginForm.controls; }

  /**
   * Get user session and return defer promise
   * @returns {.$q@call;defer.promise}
   */
  checkAdminSession() {
    return new Promise((resolve) => {
      var r = this.sessionService.getAdminSession();
      r.then(() => {
        this.adminSession = this.sessionService.getAdminSessionObj();
        resolve(this.adminSession);
      });
    })
  }

   /**
   * Check session and redirect the user if true
   * @returns {undefined}
   */
   getAdminSession() {
    this.checkAdminSession().then( (res) => {
        this.footerData.sitename = this.adminSession.sitename;
        this.dataTransmitter.sitename.next(this.adminSession.sitename);
        if(this.adminSession.logged_in === true && this.adminSession.adminarea === "Active") {
            window.location.href = this.adminHomePage;
        } else {
            this.renderMe= true;
            this.localStorageService.clear();
        }
    }, function (err) {
        /**if your asynchronous function returns defer.reject()
        instead of defer.resolve() you can catch the error here**/
    });
  };

  /**
   * Method introduced as part of TRX-6404
   * Method to authenticate Admin User Login
   * Checks whether Username/Password given by user or not
   * and validates captcha if all the credentials entered by user
   * then checks login Authenction and redirect to corresponding pages as per the response
   * 
   * @param object loginForm
   * 
   * @return void
  */
  validateLogin(loginForm: FormGroup): void {
    this.isSubmitted = true;
    if (loginForm.valid && this.validateCaptcha(loginForm.controls['captchaInput'].value)){
      this.getAuthAdminPromise(loginForm.controls['userName'].value, loginForm.controls['password'].value).then((res:any) => {
        if (res.data.message !== undefined && res.data.message !== "" && res.data.message !== null) {
          this.config.errorMessage = res.data.message;
          this.authenticate = false;
          this.captchaComponent.getCaptcha();
          this.captchaInput = "";
        } else {
            window.location.href = this.adminHomePage;
        }
      }),
       (err:any) => {
        /**if your asynchronous function returns defer.reject()
        instead of defer.resolve() you can catch the error here**/
        this.loginService.errorCallBack(err);
      };
    }
  };

  /**
   * Method introduced as part of TRX-6404
   * Method validates captcha with user given captcha input
   * 
   * @param string captchaInput
   * @returns {boolean}
  */
  validateCaptcha(captchaInput: string) {
    this.config.errorMessage = "";
    this.authenticate = true;
    if (captchaInput !== this.captcha) {
        this.config.errorMessage = "Please Enter Valid Captcha.";
        this.authenticate = false;
        return false;
    }
    return true;
  };

  /**
   * return session object as a promise
   * @returns {object.promise|$q@call;defer.promise}
  */
  getAuthAdminPromise(userName: string, password: string) {
    return new Promise((resolve) => {
      this.loginService.authenticateAdminUser(userName, password)
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: any) => {
          resolve(res);
        },
        error: (err: HttpErrorResponse) => {
          location.reload();
        },
        complete: () => { }
      });
    })
  };

  /**
  * Enable/Disable Password By clicking Eye icon
  */
  toggleShowPassword() {
    this.showPassword = !this.showPassword;
  };
}
