//--------------------------------------------------------------------------------------------------
// Copyright (c) id3 Technologies
// All Rights Reserved.
//--------------------------------------------------------------------------------------------------
// ignore_for_file: unused_import
import 'dart:convert';
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';

final _finalizer = NativeFinalizer(documentSDK.addresses.id3DocumentTextField_Dispose.cast());

/// Represents a text field extracted from a document.
class TextField implements Finalizable {
  /// Native handle.
  late Pointer<Pointer<id3DocumentTextField>> _pHandle;
  bool _disposable = true;

  /// Gets the native handle.
  /// return The native handle.
  Pointer<id3DocumentTextField> get handle => _pHandle.value;

  /// Creates a new instance of the TextField class.
  ///
  /// throws DocumentException An error has occurred during Document Library execution.
  TextField() {
    _pHandle = calloc();
    try {
      var err = documentSDK.id3DocumentTextField_Initialize(_pHandle);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
      _finalizer.attach(this, _pHandle.cast(), detach: this);
    } finally {}
  }

  /// Creates a new instance of the TextField class.
  ///
  /// param handle     Handle to the TextField.
  /// throws DocumentException An error has occurred during Document Library execution.
  TextField.fromHandle(Pointer<id3DocumentTextField> handle) {
    _pHandle = calloc();
    _pHandle.value = handle;
    _disposable = false;
  }

  /// Releases all resources used by this TextField.
  void dispose() {
    if (_disposable) {
      documentSDK.id3DocumentTextField_Dispose(_pHandle);
      calloc.free(_pHandle);
      _finalizer.detach(this);
    }
  }

  // Copyable methods

  /// Creates a copy of the TextField object.
  ///
  /// return The newly created TextField object.
  /// throws DocumentException An error has occurred during Document Library execution.
  TextField clone() {
    TextField clone = TextField();
    var err = documentSDK.id3DocumentTextField_CopyTo(_pHandle.value, clone.handle);
    if (err != DocumentError.success.value) {
      throw DocumentException(err);
    }
    return clone;
  }


  ///
  /// Boundaries of the text field in the image.
  ///
  /// throws DocumentException An error has occurred during Document Library execution.
  Rectangle get bounds => getBounds();

  ///
  /// Confidence score for the value read from the text field.
  ///
  /// throws DocumentException An error has occurred during Document Library execution.
  double get confidence => getConfidence();

  ///
  /// Name of the text field.
  ///
  /// throws DocumentException An error has occurred during Document Library execution.
  String get name => getName();

  ///
  /// Value of the text field.
  ///
  /// throws DocumentException An error has occurred during Document Library execution.
  String get value => getValue();

  // Public methods
  /// Gets the boundaries of the text field in the image.
  ///
  /// return Boundaries of the text field in the image.
  /// throws DocumentException An error has occurred during Document Library execution.
  Rectangle getBounds() {
    Pointer<id3DocumentRectangle> pBounds = calloc();
    var err = documentSDK.id3DocumentTextField_GetBounds(_pHandle.value, pBounds);
    if (err != DocumentError.success.value) {
    	calloc.free(pBounds);
    	throw DocumentException(err);
    }
    return Rectangle(pBounds);
  }

  /// Gets the confidence score for the value read from the text field.
  ///
  /// return Confidence score for the value read from the text field.
  /// throws DocumentException An error has occurred during Document Library execution.
  double getConfidence() {
    Pointer<Float> pConfidence = calloc();
    try {
      var err = documentSDK.id3DocumentTextField_GetConfidence(_pHandle.value, pConfidence);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
      final vConfidence = pConfidence.value;
      return vConfidence;
    } finally {
      calloc.free(pConfidence);
    }
  }

  /// Gets the name of the text field.
  ///
  /// return Name of the text field.
  /// throws DocumentException An error has occurred during Document Library execution.
  String getName() {
    Pointer<Char> pName = nullptr;
    Pointer<Int> pNameSize = calloc.allocate(1);
    pNameSize[0] = -1;
    try {
      var err = documentSDK.id3DocumentTextField_GetName(_pHandle.value, pName, pNameSize);
      if (err == DocumentError.insufficientBuffer.value) {
        pName = calloc.allocate(pNameSize.value);
        err = documentSDK.id3DocumentTextField_GetName(_pHandle.value, pName, pNameSize);
        if (err != DocumentError.success.value) {
          throw DocumentException(err);
        }
      }
      final vName = utf8.decode(Uint8List.fromList(pName.cast<Uint8>().asTypedList(pNameSize.value)));
      return vName;
    } finally {
      calloc.free(pName);
      calloc.free(pNameSize);
    }
  }

  /// Gets the value of the text field.
  ///
  /// return Value of the text field.
  /// throws DocumentException An error has occurred during Document Library execution.
  String getValue() {
    Pointer<Char> pValue = nullptr;
    Pointer<Int> pValueSize = calloc.allocate(1);
    pValueSize[0] = -1;
    try {
      var err = documentSDK.id3DocumentTextField_GetValue(_pHandle.value, pValue, pValueSize);
      if (err == DocumentError.insufficientBuffer.value) {
        pValue = calloc.allocate(pValueSize.value);
        err = documentSDK.id3DocumentTextField_GetValue(_pHandle.value, pValue, pValueSize);
        if (err != DocumentError.success.value) {
          throw DocumentException(err);
        }
      }
      final vValue = utf8.decode(Uint8List.fromList(pValue.cast<Uint8>().asTypedList(pValueSize.value)));
      return vValue;
    } finally {
      calloc.free(pValue);
      calloc.free(pValueSize);
    }
  }

}

