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

import 'package:fis_common/logger/logger.dart';
import 'package:vnoteapp/architecture/storage/file_storage.dart';

/// 文本存储
class TextStorage {
  TextStorage({
    required this.fileName,
    this.directory = "",
  });

  final String fileName;
  final String directory;

  FileStorage? _fileStorage;

  Future<bool> save(String text) async {
    try {
      final bytes = Uint8List.fromList(utf8.encode(text));
      _fileStorage ??= FileStorage(directory: directory);
      final result = await _fileStorage!.save(fileName, bytes);
      return result;
    } catch (e) {
      logger.e("TextStorage save text error.", e);
      return false;
    }
  }

  Future<String?> read() async {
    _fileStorage ??= FileStorage(directory: directory);
    final bytes = await _fileStorage!.read(fileName);
    if (bytes == null || bytes.isEmpty) return null;

    try {
      final str = utf8.decode(bytes);
      return str;
    } catch (e) {
      logger.e("TextStorage convert bytes to string error.", e);
      return null;
    }
  }
}
