// 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';
import 'package:wyatt_type_utils/src/extensions/iterable_extension.dart';

extension StringExtension on String? {
  /// Returns true if this string is either null or empty.
  bool get isNullOrEmpty => this == null || this!.isEmpty;

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

  /// Converts a [String] to a [Uint8List] using the specified [Encoding].
  Uint8List toBytes({final Encoding from = Encoding.utf16}) {
    Uint8List bytes;
    switch (from) {
      case Encoding.utf8:
        bytes = utf8.encode(this ?? '').toTypedList();
        break;
      case Encoding.utf16:
        bytes = (this ?? '').runes.toList().toTypedList();
        break;
      case Encoding.base64:
        bytes = base64.decode(this ?? '');
        break;
      case Encoding.base16:
        assert(
          (this ?? '').length.isEven,
          'String needs to be an even length.',
        );
        bytes = List.generate(
          (this ?? '').length ~/ 2,
          (i) =>
              int.parse((this ?? '').substring(i * 2, (i * 2) + 2), radix: 16),
        ).toList().toTypedList();
    }
    return bytes;
  }
}
