import 'dart:convert';

import 'package:logger/logger.dart';

class WyattPrinter extends LogPrinter {
  WyattPrinter({this.colors = true});

  final bool colors;

  static Logger? _instance;

  /// Returns [Logger] instance or create it if not.
  static Logger get({bool colors = true}) {
    _instance ??= Logger(printer: WyattPrinter(colors: colors));
    return _instance!;
  }

  @override
  List<String> log(LogEvent event) {
    // final classNameStr = (className != null) ? '$className ' : '';
    final messageStr = _stringifyMessage(event.message);
    final errorStr = event.error != null ? 'ERROR: ${event.error}' : '';
    return ['${_labelFor(event.level)} $messageStr$errorStr'];
  }

  String _labelFor(Level level) {
    final prefix = PrettyPrinter.levelEmojis[level]!;
    final color = PrettyPrinter.levelColors[level]!;

    return colors ? color(prefix) : prefix;
  }

  String _stringifyMessage(dynamic message) {
    // ignore: avoid_dynamic_calls
    final finalMessage = message is Function ? message() : message;
    if (finalMessage is Map || finalMessage is Iterable) {
      const encoder = JsonEncoder.withIndent(null);
      return encoder.convert(finalMessage);
    } else {
      return finalMessage.toString();
    }
  }
}
