import { action } from '@ember/object';
import { service } from '@ember/service';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import '@simplewebauthn/browser';
import {
  startAuthentication,
  startRegistration,
} from '@simplewebauthn/browser';
import type AuthService from 'frontend-reactive/services/auth';

export interface AuthSignature {
  // The arguments accepted by the component
  Args: {};
  // Any blocks yielded by the component
  Blocks: {
    default: [];
  };
  // The element to which `...attributes` is applied in the component template
  Element: null;
}

export default class Auth extends Component<AuthSignature> {
  @tracked username: string = '';
  @tracked error: string | undefined;
  //@tracked isLogin = true;
  @service declare auth: AuthService;

  @action async startLogin() {
    try {
      // TODO: Check if account exists and is alowed to login
      this.auth.startLogin(this.username);
    } catch (error: any) {
      this.error = 'Error: ' + error.message;
    }
  }

  @action async startRegistration() {
    try {
      // TODO: Check if handle is already taken
      await this.auth.startRegistration(this.username);
      // After registration, log in immediately to obtain a valid session token
      // for the "post" registration data, such as email
      await this.auth.startLogin(this.username);
      // And after login,
    } catch (error: any) {
      this.error = 'Error: ' + error.message;
    }
  }
}
