import {Component, ElementRef, EventEmitter, Output, ViewChild} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Router} from "@angular/router";
import {AuthService} from "./auth.service";
import {NgbModal} from "@ng-bootstrap/ng-bootstrap";

@Component({
  selector: 'login',
  template: `
      <button *ngIf="!isAuthenticated" 
              class="nav-link px-3 w-100" 
              (click)="openLoginModal()"
      ><i-bs name="key-fill"/><span class="ms-1 d-none d-sm-inline" i18n>Login</span></button>
      <ng-template #loginModal let-modal>
          <div class="modal-header">
              <h4 class="modal-title" id="modal-basic-title" i18n>Login</h4>
              <button type="button" class="btn-close" aria-label="Close"
                      (click)="modal.dismiss('Cross click')"></button>
          </div>
          <div class="modal-body">
            <form [formGroup]="form">
                <fieldset>
                    <div class="form-field">
                        <label i18n>Username:</label>
                        <input class="form-control" name="username" formControlName="username">
                    </div>
                    <div class="form-field">
                        <label i18n>Password:</label>
                        <input class="form-control" name="password" formControlName="password" 
                               type="password">
                    </div>
                </fieldset>
            </form>
          </div>
          <div class="modal-footer">
                <div class="form-buttons">
                    <button class="btn btn-primary" 
                            (click)="this.login()" i18n>Login</button>
                </div>
                <div class="form-buttons">
                    <button class="btn btn-danger" 
                            (click)="modal.dismiss('Cancel click')" i18n>Cancel</button>
                </div>
          </div>
      </ng-template>
    `
})
export class LoginComponent {
    @Output() loginSuccess = new EventEmitter<string>()

    @ViewChild('loginModal')
    loginModal!: ElementRef;

    form: FormGroup;

    isAuthenticated: boolean = false

    constructor(private fb:FormBuilder,
                 private authService: AuthService,
                private modalService: NgbModal

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

        this.authService.onAuthenticationRequired$.subscribe((required: boolean) => {
            if (required) {
                this.openLoginModal();
            }
        })
        this.isAuthenticated = this.authService.is_authenticated;
        this.authService.onIsAuthenticated$.subscribe((isAuthenticated: boolean) => {
            this.isAuthenticated = isAuthenticated;
        })
    }

    openLoginModal() {
		this.modalService.open(this.loginModal, { ariaLabelledBy: 'modal-basic-title' }).result.then(
		);
	}

    login() {
        const val = this.form.value;

        if (val.username && val.password) {
            this.authService.login(val.username, val.password)
                .subscribe((answer: string) => {
                        this.form.reset();
                        this.modalService.dismissAll();
                        this.loginSuccess.emit(answer)
                    }
                );
        }
    }
}

@Component({
  selector: 'logout',
  template: `
        <button *ngIf="isAuthenticated" 
                class="nav-link px-3 w-100" 
                (click)="logout()"
        ><i-bs name="door-open-fill"/><span class="ms-1 d-none d-sm-inline" i18n>Logout</span></button>
    `
})
export class LogoutComponent {
    @Output() logoutSuccess = new EventEmitter()
    isAuthenticated: boolean = false

    constructor(private authService: AuthService) {
        this.isAuthenticated = this.authService.is_authenticated;
        this.authService.onIsAuthenticated$.subscribe((isAuthenticated: boolean) => {
            this.isAuthenticated = isAuthenticated
        })
    }

    logout() {
        this.authService.logout()
            .subscribe(() => {
                    this.logoutSuccess.emit()
                }
            );
    }
}
