/// Native (dart:io) renderer-settings persistence.
library;

import 'dart:io';

import 'package:wolf_3d_dart/src/engine/rendering/renderer_settings.dart';
import 'package:wolf_3d_dart/src/engine/rendering/renderer_settings_persistence.dart';
import 'package:wolf_3d_dart/src/platform/platform_config_dir.dart';

/// Persists [WolfRendererSettings] as JSON to the platform config directory.
///
/// Pass an explicit [filePath] to override the default location (useful in tests).
class DefaultRendererSettingsPersistence extends RendererSettingsPersistence
    with JsonRendererSettingsPersistence {
  DefaultRendererSettingsPersistence({String? filePath}) : _filePath = filePath;

  final String? _filePath;
  String? _resolvedPath;

  Future<String> _getFilePath() async {
    if (_resolvedPath != null) return _resolvedPath!;
    _resolvedPath = _filePath ?? '${platformConfigDir()}/settings.json';
    return _resolvedPath!;
  }

  @override
  Future<String?> readRaw() async {
    try {
      final String path = await _getFilePath();
      final File f = File(path);
      if (!f.existsSync()) return null;
      return await f.readAsString();
    } catch (_) {
      return null;
    }
  }

  @override
  Future<void> writeRaw(String json) async {
    try {
      final String path = await _getFilePath();
      final Directory dir = File(path).parent;
      if (!dir.existsSync()) await dir.create(recursive: true);
      await File(path).writeAsString(json, flush: true);
    } catch (_) {
      // Best-effort.
    }
  }
}
