import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActionsLayout, DialogService } from '@progress/kendo-angular-dialog';
import { AuthService } from 'src/app/auth/services/auth.service';
import { ResultApi } from 'src/app/models/result-api.model';
import { User } from 'src/app/models/user.model';

@Component({
  selector: 'app-auth-user',
  templateUrl: './auth-user.component.html',
  styleUrls: ['./auth-user.component.scss']
})
export class AuthUserComponent implements OnInit {
  @Input() opened = false;
  @Output() resultEvent = new EventEmitter<User>();
  user: any;
  formAuth: FormGroup;
  openedDialog = false;
  public loadingIcon = '';

  public actionsLayout: ActionsLayout = 'normal';

  public onDialogClose(): void {
    this.resultEvent.emit(null);
  }

  public onDeleteData(): void {
    this.opened = false;
    this.resultEvent.emit(this.user);
  }

  public open(): void {
    this.opened = true;
  }

  public closeDialog() {
    this.openedDialog = false;
  }
  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private dialogService: DialogService
    ) {
    this.formAuth = this.fb.group({
      email: [''],
      password: [''],
    });
  }

  ngOnInit(): void {
  }

  login() {
    this.loadingIcon = 'loading';
    this.authService.login({
      email: this.formAuth.value.email,
      password: this.formAuth.value.password
    })
      .subscribe((res: ResultApi) => {
        if (res.success) {
          this.loadingIcon = '';
          this.opened = false;
          this.user = res.data;
          this.resultEvent.emit(this.user);
        } else {
          this.loadingIcon = '';
          this.openedDialog = true;
        }
      }, err => {
        this.openedDialog = true;
        this.loadingIcon = '';
      });
  }

}
