// Dart imports:
import 'dart:convert';
import 'dart:io';

// Flutter imports:
import 'package:flutter/widgets.dart';

// Package imports:
import 'package:path_provider/path_provider.dart';
import 'package:talker_flutter/talker_flutter.dart';

class CustomHistory implements TalkerHistory {
  CustomHistory(this.settings, {List<TalkerData>? history}) {
    if (history != null) {
      _history.addAll(history);
    }
  }

  final TalkerSettings settings;

  final List<TalkerData> _history = <TalkerData>[];

  @override
  List<TalkerData> get history => _history;

  @override
  void clean() async {
    if (settings.useHistory) {
      _history.clear();

      final Directory docDir = await getApplicationDocumentsDirectory();

      final String path = '${docDir.path}/history.log';

      final File logFile = File(path);

      if (logFile.existsSync()) {
        logFile.deleteSync();
      }
    }
  }

  @override
  void write(TalkerData data) {
    if (settings.useHistory && settings.enabled) {
      if (settings.maxHistoryItems <= _history.length) {
        _history.removeAt(0);
      }

      _history.add(data);

      _writeToFile(data);
    }
  }

  void _writeToFile(TalkerData data) async {
    try {
      final Directory docDir = await getApplicationDocumentsDirectory();

      final String path = '${docDir.path}/history.log';

      final File logFile = File(path);

      if (!logFile.existsSync()) {
        logFile.createSync();
      }

      final Map<String, dynamic> jData = <String, dynamic>{
        'error': data.error,
        'exception': data.exception,
        'logLevel': data.logLevel,
        'key': data.key,
        'message': data.message,
        'stackTrace': data.stackTrace,
        'title': data.title,
        'time': data.time.toString(),
      };

      logFile.writeAsStringSync(
        '${jsonEncode(jData)}\n',
        mode: FileMode.writeOnlyAppend,
      );
    } catch (e) {
      debugPrint('ALARMA ERROR in _writeToFile customHistory $e');
    }
  }
}
