// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'dart:convert';
import 'dart:typed_data';

import 'package:wyatt_type_utils/src/extensions/encoding.dart';

extension IterableExtension<T> on Iterable<T?>? {
  /// Returns true if this nullable iterable is either null or empty.
  bool get isNullOrEmpty => this == null || this!.isEmpty;

  /// Returns false if this nullable iterable is either null or empty.
  bool get isNotNullOrEmpty => this != null && this!.isNotEmpty;
}

extension IterableIntExtension on Iterable<int>? {
  /// Converts an [Iterable] of [int] to a [Uint8List].
  Uint8List toTypedList() => Uint8List.fromList(this?.toList() ?? []);

  /// Converts a [Uint8List] to a [String] using the specified [Encoding].
  String toStr({final Encoding to = Encoding.utf16}) {
    String str;
    switch (to) {
      case Encoding.utf8:
        str = utf8.decode(this?.toList() ?? []);
        break;
      case Encoding.utf16:
        str = String.fromCharCodes(this ?? []);
        break;
      case Encoding.base64:
        str = base64.encode(this?.toList() ?? []);
        break;
      case Encoding.base16:
        str = List.generate(
          (this ?? []).length,
          (i) => (this ?? []).elementAt(i).toRadixString(16).padLeft(2, '0'),
        ).join();
    }
    return str;
  }
}
