import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { FuseAlertType } from '@fuse/components/alert';
import { AuthService } from 'app/core/auth/auth.service';

@Component({
  selector: 'sign-in-compose',
  templateUrl: './sign-in-compose.component.html',
  encapsulation: ViewEncapsulation.None,
})
export class SignInComposeComponent implements OnInit {
  signInComposeForm!: FormGroup;

  alert: { type: FuseAlertType; message: string } = {
    type: 'success',
    message: '로그인이 성공하였습니다.',
  };

  showAlert: boolean = false;

  /**
   * Constructor
   */
  constructor(
    public matDialogRef: MatDialogRef<SignInComposeComponent>,
    private _formBuilder: FormBuilder,
    private _authService: AuthService
  ) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    // Create the form
    this.signInComposeForm = this._formBuilder.group({
      username: ['', [Validators.required]],
      password: ['', [Validators.required]],
    });
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Save and close
   */
  saveAndClose(): void {
    // Save the message as a draft
    this.saveAsDraft();

    // Close the dialog
    this.matDialogRef.close();
  }

  /**
   * Discard the message
   */
  discard(): void {}

  /**
   * Save the message as a draft
   */
  saveAsDraft(): void {}

  /**
   * Send the message
   */
  send(): void {
    // Return if the form is invalid
    if (this.signInComposeForm?.invalid) {
      return;
    }

    // Disable the form
    this.signInComposeForm?.disable();

    // Sign in
    this._authService
      .signIn(this.signInComposeForm?.value)
      .then(() => {
        console.log();
        this.showAlert = true;
      })
      .catch((e) => {
        this.showAlert = true;
        this.alert = { type: 'error', message: '등록에 실패하였습니다.' };
        // Re-enable the form
        this.signInComposeForm?.enable();

        // Reset the form
      });
  }
}
