//--------------------------------------------------------------------------------------------------
// 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 'document_sdk_generated_bindings.dart';
import 'document_native.dart';

import '../id3_document.dart';

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

/// Represents a string dictionary.
class StringDict extends Object with IterableMixin<String> implements Finalizable {
  /// Native handle.
  late Pointer<Pointer<id3DocumentStringDict>> _pHandle;
  bool _disposable = true;

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

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

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

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

  // Copyable methods

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

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

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

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

  ///
  /// Gets a string list containing the keys in the dict.
  ///
  /// throws DocumentException An error has occurred during Document Library execution.
  StringList get keys => getKeys();

  // Public methods
  /// Clears the StringDict object.
  ///
  /// throws DocumentException An error has occurred during Document Library execution.
  void clear() {
    var err = documentSDK.id3DocumentStringDict_Clear(_pHandle.value);
    if (err != DocumentError.success.value) {
      throw DocumentException(err);
    }
  }

  /// Adds an item to the StringDict object.
  ///
  /// param key Unique key of the  item to add.
  /// param item  item to add.
  /// throws DocumentException An error has occurred during Document Library execution.
  void add(String? key, String? item) {
    Pointer<Char>? pKey = key?.toNativeUtf8().cast<Char>();
    Pointer<Char>? pItem = item?.toNativeUtf8().cast<Char>();
    try {
      var err = documentSDK.id3DocumentStringDict_Add(_pHandle.value, pKey ?? nullptr, pItem ?? nullptr);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
    } finally {
      if (pKey != null) {
        calloc.free(pKey);
      }
      if (pItem != null) {
        calloc.free(pItem);
      }
    }
  }

  /// Gets an item of the StringDict object.
  ///
  /// param key Unique key of the  item to get.
  /// return  item to get.
  /// throws DocumentException An error has occurred during Document Library execution.
  String get(String? key) {
    Pointer<Char>? pKey = key?.toNativeUtf8().cast<Char>();
    Pointer<Char> pItem = nullptr;
    Pointer<Int> pItemSize = calloc.allocate(1);
    pItemSize[0] = -1;
    try {
      var err = documentSDK.id3DocumentStringDict_Get(_pHandle.value, pKey ?? nullptr, pItem, pItemSize);
      if (err == DocumentError.insufficientBuffer.value) {
        pItem = calloc.allocate(pItemSize.value);
        err = documentSDK.id3DocumentStringDict_Get(_pHandle.value, pKey ?? nullptr, pItem, pItemSize);
        if (err != DocumentError.success.value) {
          throw DocumentException(err);
        }
      }
      final vItem = utf8.decode(Uint8List.fromList(pItem.cast<Uint8>().asTypedList(pItemSize.value)));
      return vItem;
    } finally {
      if (pKey != null) {
        calloc.free(pKey);
      }
      calloc.free(pItem);
      calloc.free(pItemSize);
    }
  }

  /// Sets an item of the StringDict object.
  ///
  /// param key Unique key of the  item to set.
  /// param item  item to set.
  /// throws DocumentException An error has occurred during Document Library execution.
  void set(String? key, String? item) {
    Pointer<Char>? pKey = key?.toNativeUtf8().cast<Char>();
    Pointer<Char>? pItem = item?.toNativeUtf8().cast<Char>();
    try {
      var err = documentSDK.id3DocumentStringDict_Set(_pHandle.value, pKey ?? nullptr, pItem ?? nullptr);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
    } finally {
      if (pKey != null) {
        calloc.free(pKey);
      }
      if (pItem != null) {
        calloc.free(pItem);
      }
    }
  }

  /// Gets the number of elements in the StringDict object.
  ///
  /// return Number of elements in the  object.
  /// throws DocumentException An error has occurred during Document Library execution.
  int getCount() {
    Pointer<Int> pCount = calloc();
    try {
      var err = documentSDK.id3DocumentStringDict_GetCount(_pHandle.value, pCount);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
      final vCount = pCount.value;
      return vCount;
    } finally {
      calloc.free(pCount);
    }
  }

  /// Determines whether the StringDictobject contains the specified key.
  ///
  /// param key The key to locate in the  object.
  /// return true if the  object contains an element with the specified key, otherwise false.
  /// throws DocumentException An error has occurred during Document Library execution.
  bool containsKey(String? key) {
    Pointer<Char>? pKey = key?.toNativeUtf8().cast<Char>();
    Pointer<Bool> pResult = calloc();
    try {
      var err = documentSDK.id3DocumentStringDict_ContainsKey(_pHandle.value, pKey ?? nullptr, pResult);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
      final vResult = pResult.value;
      return vResult;
    } finally {
      if (pKey != null) {
        calloc.free(pKey);
      }
      calloc.free(pResult);
    }
  }

  /// Removes an element of the StringDict object.
  ///
  /// param key Unique key of the  item to remove.
  /// throws DocumentException An error has occurred during Document Library execution.
  void remove(String? key) {
    Pointer<Char>? pKey = key?.toNativeUtf8().cast<Char>();
    try {
      var err = documentSDK.id3DocumentStringDict_Remove(_pHandle.value, pKey ?? nullptr);
      if (err != DocumentError.success.value) {
        throw DocumentException(err);
      }
    } finally {
      if (pKey != null) {
        calloc.free(pKey);
      }
    }
  }

  /// Gets the gets a string list containing the keys in the dict.
  ///
  /// return Gets a string list containing the keys in the dict.
  /// throws DocumentException An error has occurred during Document Library execution.
  StringList getKeys() {
    StringList keys = StringList();
    var err = documentSDK.id3DocumentStringDict_GetKeys(_pHandle.value, keys.handle);
    if (err != DocumentError.success.value) {
      keys.dispose();
      throw DocumentException(err);
    }
    return keys;
  }

}

class StringDictIterator implements Iterator<String> {
  StringDictIterator(this._list)
      : _count = _list.getCount(),
        _keys = [] {
    final StringList keys = _list.getKeys();
    for (var key in keys) {
      _keys.add(key);
    }
    keys.dispose();
  }
  final StringDict _list;
  final int _count;
  int _index = -1;
  final List<String> _keys;

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

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