import {
    Component, OnInit, ViewChild, ElementRef,
    ChangeDetectorRef, ChangeDetectionStrategy
} from '@angular/core'
import { Router } from '@angular/router'

import { UntypedFormGroup, UntypedFormControl, Validators } from '@angular/forms'

import { ConfigService } from '../config.service'
import { AuthenticationService } from '../_services/authentication.service'

@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})

export class LoginComponent implements OnInit {
    loading = false
    error = ''

    formGroup: UntypedFormGroup
    @ViewChild('userName', { static: true }) userName: ElementRef

    constructor(
        public configService: ConfigService,
        private router: Router,
        private authenticationService: AuthenticationService,
        private cdr: ChangeDetectorRef,
    ) { }

    ngOnInit() {
        this.userName.nativeElement.focus()
        this.formGroup = new UntypedFormGroup({
            userName: new UntypedFormControl('', Validators.required),
            password: new UntypedFormControl('', Validators.required),
        })
    }

    submit() {
        this.loading = true
        this.authenticationService.login(this.formGroup.value.userName, this.formGroup.value.password).subscribe({
            next: result => {
                if (result === true) {
                    // login successful
                    this.router.navigate(['/'])
                } else {
                    // login failed
                    this.error = 'User name or password is incorrect'
                    this.loading = false
                    this.cdr.markForCheck()
                }
            },
            error: error => {
                console.error(error)
                this.error = error.statusText
                this.loading = false
                this.cdr.markForCheck()
            }
        })
    }
}
