import { Inject, Injectable } from '@angular/core';
import { ScanAdapter } from './scan-adapter';
import { SCAN_ADAPTER } from './tokens';

@Injectable({
  providedIn: 'root',
})
export class ScanAdapterService {
  constructor(@Inject(SCAN_ADAPTER) private readonly scanAdapters: ScanAdapter[]) {}

  scanners() {
    return this.scanAdapters.filter((adapter) => adapter.isReady());
  }

  scanner() {
    return this.scanners().find((scanner) => scanner.isPrimary()) || this.scanners().find(() => true);
  }

  isReady() {
    return this.scanAdapters.some((adapter) => adapter.isReady());
  }

  scan() {
    const primaryScanner = this.scanner();
    if (primaryScanner) {
      return primaryScanner.scan();
    }
    return null;
  }
}
