import { TransactionsService } from './transactions.service';
import { defaultOnRetry, defaultOnSuccess } from '../constants';
import { EBiometricsEnvironment, EBiometricsInput, EBiometricsProvider, EBiometricsQueue, EBiometricsState, EBiometricsTheme } from '../models';

export class ValidatorService {
  private _transactionsService: TransactionsService

  constructor() {
    this._transactionsService = new TransactionsService();
  }

  private _error(message: string): void {
    throw new Error(message);
  }

  async getState(input: EBiometricsInput): Promise<EBiometricsState> {
    if (!input.target) this._error('You must provide the target element ID');
    if (!input.account) this._error('You must provide the account UUID');
    if (!input.params) this._error('You must provide the params');

    input.theme = input.theme ?? EBiometricsTheme.light;
    input.provider = input.provider ?? EBiometricsProvider.softcol;
    input.queue = input.queue ?? EBiometricsQueue.simple;
    input.environment = input.environment ?? EBiometricsEnvironment.development;
    input.extraInfo = input.extraInfo ?? '';
    input.onRetry = input.onRetry ?? defaultOnRetry;
    input.onSuccess = input.onSuccess ?? defaultOnSuccess;

    const state = input as EBiometricsState;
    const transaction = await this._transactionsService.create(state);
    state.id = transaction.id
    
    const targetEl = document.getElementById(state.target);
    if (!targetEl) this._error(`Could not find HTML element with ID: ${state.target}`);
    state.targetEl = targetEl as HTMLElement;

    return state;
  }
}
