//--------------------------------------------------------------------------------------------------
// Copyright (c) id3 Technologies
// All Rights Reserved.
//--------------------------------------------------------------------------------------------------
// ignore_for_file: unused_import
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'document_sdk_generated_bindings.dart';
import 'document_native.dart';

import '../id3_document.dart';

/// Provides functionalities to decode and check a MRZ.
class MrzHelper {

  // Public methods
  /// Checks the validity of a single line of an MRZ of a given type by checking the check digits.
  ///
  /// param text The input MRZ line.
  /// param type The input MRZ type according to ICAO-9303 standard.
  /// return The result of the verification.
  /// throws DocumentException An error has occurred during Document Library execution.
  static bool check(String? text, MrzType type) {
    Pointer<Char>? pText = text?.toNativeUtf8().cast<Char>();
    Pointer<Bool> pValidity = calloc();
    try {
      var err = documentSDK.id3DocumentMrzHelper_Check(pText ?? nullptr, type.value, pValidity);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
      final vValidity = pValidity.value;
      return vValidity;
    } finally {
      if (pText != null) {
        calloc.free(pText);
      }
      calloc.free(pValidity);
    }
  }

  /// Decodes an MRZ of a given type and returns the values of the various fields.
  ///
  /// param text The input MRZ.
  /// param type The input MRZ type according to ICAO-9303 standard.
  /// return A dictionary containing the fields and values decoded in the MRZ.
  /// throws DocumentException An error has occurred during Document Library execution.
  static StringDict decode(String? text, MrzType type) {
    Pointer<Char>? pText = text?.toNativeUtf8().cast<Char>();
    StringDict fields = StringDict();
    try {
      var err = documentSDK.id3DocumentMrzHelper_Decode(pText ?? nullptr, type.value, fields.handle);
      if (err != DocumentError.success.value) {
        fields.dispose();
        throw DocumentException(err);
      }
      return fields;
    } finally {
      if (pText != null) {
        calloc.free(pText);
      }
    }
  }

}

