import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'
import { LoggerService } from '../../services/logger.service'
import { Subscription } from 'rxjs'

import { SasService } from '../../services/sas.service'

interface User {
  user: string | null
  pass: string | null
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class LoginComponent implements OnInit, OnDestroy {
  private _subscription: Subscription = new Subscription()
  public isActive: boolean | undefined
  public loading: boolean = false
  public alertClosed: boolean = true
  public errorMsg: string | undefined
  public data: User = {
    user: null,
    pass: null
  }

  constructor(
    private sasService: SasService,
    private loggerService: LoggerService
  ) {}

  ngOnInit() {
    let sasjsConfig = this.sasService.getSasjsConfig()

    if (sasjsConfig.loginMechanism !== 'Redirected') {
      this._subscription = this.sasService.shouldLogin.subscribe(
        (shouldLogin) => {
          this.isActive = shouldLogin

          let bodyEl = document.querySelector('body')

          if (!bodyEl) return

          if (shouldLogin) {
            bodyEl.classList.add('should-login')
          } else {
            bodyEl.classList.remove('should-login')
          }
        }
      )
    }
  }

  ngOnDestroy() {
    this._subscription.unsubscribe()
  }

  public submit() {
    if (this.loading) {
      return
    }

    this.loading = true

    if (this.data.user && this.data.pass) {
      this.sasService.login(this.data.user, this.data.pass).then(
        (isLoggedIn: any) => {
          this.loading = false

          if (!isLoggedIn) {
            this.errorMsg = 'Username or password invalid'
            this.alertClosed = false
          }
        },
        (err: any) => {
          this.loggerService.log(err)

          this.loading = false
          this.errorMsg = err
          this.alertClosed = false
        }
      )
    }
  }
}
