//--------------------------------------------------------------------------------------------------
// Copyright (c) id3 Technologies
// All Rights Reserved.
//--------------------------------------------------------------------------------------------------
// ignore_for_file: unused_import
import 'dart:collection';
import 'dart:convert';
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'bioseal_sdk_generated_bindings.dart';
import 'bioseal_native.dart';

import '../id3_bioseal.dart';

final _finalizer = NativeFinalizer(biosealSDK.addresses.id3BiosealStringArray_Dispose.cast());

/// Represents an array of strings.
class StringArray extends Object with IterableMixin<String> implements Finalizable {
  /// Native handle.
  late Pointer<Pointer<id3BiosealStringArray>> _pHandle;
  bool _disposable = true;

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

  /// Creates a new instance of the StringArray class.
  ///
  /// throws BiosealException An error has occurred during Bioseal Library execution.
  StringArray() {
    _pHandle = calloc();
    try {
      var err = biosealSDK.id3BiosealStringArray_Initialize(_pHandle);
      if (err != BiosealError.success.value) {
        throw BiosealException(err);
      }
      _finalizer.attach(this, _pHandle.cast(), detach: this);
    } finally {}
  }

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

  /// Releases all resources used by this StringArray.
  void dispose() {
    if (_disposable) {
      biosealSDK.id3BiosealStringArray_Dispose(_pHandle);
      calloc.free(_pHandle);
      _finalizer.detach(this);
    }
  }

  /// Gets or sets the element at the specified index.
  operator [](int key) => get(key);

  /// Gets the number of elements contained in the list or dictionary.
  int get count => getCount();

  @override
  Iterator<String> get iterator => StringArrayIterator(this);

  // Public methods
  /// Gets an item of the StringArray object.
  ///
  /// param index Index of the  item to get.
  /// return  item to get.
  /// throws BiosealException An error has occurred during Bioseal Library execution.
  String get(int index) {
    Pointer<Char> pItem = nullptr;
    Pointer<Int> pItemSize = calloc.allocate(1);
    pItemSize[0] = -1;
    try {
      var err = biosealSDK.id3BiosealStringArray_Get(_pHandle.value, index, pItem, pItemSize);
      if (err == BiosealError.insufficientBuffer.value) {
        pItem = calloc.allocate(pItemSize.value);
        err = biosealSDK.id3BiosealStringArray_Get(_pHandle.value, index, pItem, pItemSize);
        if (err != BiosealError.success.value) {
          throw BiosealException(err);
        }
      }
      final vItem = utf8.decode(Uint8List.fromList(pItem.cast<Uint8>().asTypedList(pItemSize.value)));
      return vItem;
    } finally {
      calloc.free(pItem);
      calloc.free(pItemSize);
    }
  }

  /// Gets the number of elements in the StringArray object.
  ///
  /// return Number of elements in the  object.
  /// throws BiosealException An error has occurred during Bioseal Library execution.
  int getCount() {
    Pointer<Int> pCount = calloc();
    try {
      var err = biosealSDK.id3BiosealStringArray_GetCount(_pHandle.value, pCount);
      if (err != BiosealError.success.value) {
        throw BiosealException(err);
      }
      final vCount = pCount.value;
      return vCount;
    } finally {
      calloc.free(pCount);
    }
  }

  /// Returns a value indicating whether a specified string occurs in this string array.
  ///
  /// param item The string to seek.
  /// return true if the item parameter occurs within this string array; otherwise, false.
  /// throws BiosealException An error has occurred during Bioseal Library execution.
  @override
  bool contains(Object? item) {
    String? nItem = item as String?;
    Pointer<Char>? pItem = nItem?.toNativeUtf8().cast<Char>();
    Pointer<Bool> pResult = calloc();
    try {
      var err = biosealSDK.id3BiosealStringArray_Contains(_pHandle.value, pItem ?? nullptr, pResult);
      if (err != BiosealError.success.value) {
        throw BiosealException(err);
      }
      final vResult = pResult.value;
      return vResult;
    } finally {
      if (pItem != null) {
        calloc.free(pItem);
      }
      calloc.free(pResult);
    }
  }

}

class StringArrayIterator implements Iterator<String> {
  StringArrayIterator(this._list) : _count = _list.getCount();
  final StringArray _list;
  final int _count;
  int _index = -1;

  @override
  String get current => _list.get(_index);

  @override
  bool moveNext() {
    _index++;
    return _index < _count;
  }
}
