library;

import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:wolf_3d_dart/wolf_3d_data_types.dart';
import 'package:wolf_3d_dart/wolf_3d_engine.dart';

/// Flutter desktop adapter for slot-based game save persistence.
class FlutterSaveGamePersistence implements SaveGamePersistence {
  FlutterSaveGamePersistence({String? directoryPath})
    : _directoryPath = directoryPath;

  final String? _directoryPath;
  String? _resolvedDirectoryPath;

  Future<String> _resolveDirectoryPath() async {
    if (_resolvedDirectoryPath != null) {
      return _resolvedDirectoryPath!;
    }

    if (_directoryPath != null) {
      _resolvedDirectoryPath = _directoryPath;
      return _resolvedDirectoryPath!;
    }

    _resolvedDirectoryPath = '${_platformConfigDir()}/saves';
    return _resolvedDirectoryPath!;
  }

  @override
  Future<Uint8List?> load({
    required int slot,
    required GameVersion version,
  }) async {
    if (kIsWeb) {
      return null;
    }

    try {
      final String dirPath = await _resolveDirectoryPath();
      final File file = File(_slotPath(dirPath, slot, version));
      if (!file.existsSync()) {
        return null;
      }
      return await file.readAsBytes();
    } catch (_) {
      return null;
    }
  }

  @override
  Future<bool> exists({
    required int slot,
    required GameVersion version,
  }) async {
    if (kIsWeb) {
      return false;
    }

    try {
      final String dirPath = await _resolveDirectoryPath();
      final File file = File(_slotPath(dirPath, slot, version));
      return file.existsSync() && file.lengthSync() > 0;
    } catch (_) {
      return false;
    }
  }

  @override
  Future<void> save({
    required int slot,
    required GameVersion version,
    required Uint8List bytes,
  }) async {
    if (kIsWeb) {
      return;
    }

    final String dirPath = await _resolveDirectoryPath();
    final Directory dir = Directory(dirPath);
    if (!dir.existsSync()) {
      await dir.create(recursive: true);
    }
    await File(
      _slotPath(dirPath, slot, version),
    ).writeAsBytes(bytes, flush: true);
  }

  String _slotPath(String dirPath, int slot, GameVersion version) {
    final String normalizedSlot = slot.clamp(0, 9).toString();
    return '$dirPath/SAVEGAM$normalizedSlot.${version.fileExtension}';
  }
}

String _platformConfigDir() {
  if (Platform.isLinux) {
    final String xdg = Platform.environment['XDG_CONFIG_HOME'] ?? '';
    final String home = Platform.environment['HOME'] ?? '.';
    return xdg.isNotEmpty ? '$xdg/wolf3d' : '$home/.config/wolf3d';
  }
  if (Platform.isMacOS) {
    final String home = Platform.environment['HOME'] ?? '.';
    return '$home/Library/Application Support/wolf3d';
  }
  if (Platform.isWindows) {
    final String appData = Platform.environment['APPDATA'] ?? '.';
    return '$appData/wolf3d';
  }
  final String home = Platform.environment['HOME'] ?? '.';
  return '$home/.config/wolf3d';
}
