import 'package:flame/components.dart';
import 'package:shitman/attributes/resetable.dart';
import 'package:shitman/game/levels/shit_level.dart';
import 'package:shitman/game/components/base.dart';
import 'package:shitman/services/log_service.dart';
import 'package:shitman/settings/app_settings.dart';

class ShitmanWorld extends World with Resetable, AppLogging, AppSettings {
  ShitLevel? _currentLevel;
  bool _isInitialized = false;

  /// Get the current level
  ShitLevel? get currentLevel => _currentLevel;

  /// Check if world is initialized
  bool get isInitialized => _isInitialized;

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    await initSettings();
    _isInitialized = true;
    appLog.fine('ShitmanWorld initialized');
  }

  /// Load a specific level
  Future<void> loadLevel(ShitLevel level) async {
    appLog.fine('Loading level: ${level.levelName}');
    
    // Reset current level if one exists
    if (_currentLevel != null) {
      await _currentLevel!.reset();
      _currentLevel!.removeFromParent();
    }
    
    // Set and load new level
    _currentLevel = level;
    add(_currentLevel!);
    await _currentLevel!.onLoad();
    _currentLevel!.startLevel();
    
    appLog.info('Level loaded: ${level.levelName}');
  }

  /// Unload the current level
  Future<void> unloadLevel() async {
    if (_currentLevel == null) return;
    
    appLog.fine('Unloading level: ${_currentLevel!.levelName}');
    
    _currentLevel!.endLevel();
    await _currentLevel!.reset();
    _currentLevel!.removeFromParent();
    _currentLevel = null;
    
    appLog.fine('Level unloaded');
  }

  /// Reset all components in the world that implement Resetable
  Future<void> resetAllComponents() async {
    appLog.fine('Resetting all world components');
    
    final resetableComponents = children.whereType<Resetable>().toList();
    for (final component in resetableComponents) {
      await component.reset();
    }
    
    // Also reset the current level
    if (_currentLevel != null) {
      await _currentLevel!.reset();
    }
    
    appLog.fine('All components reset');
  }

  /// Get all components of a specific type
  List<T> getComponentsOfType<T extends Component>() {
    return children.whereType<T>().toList();
  }

  /// Get all ShitComponents
  List<ShitComponent> getAllShitComponents() {
    return children.whereType<ShitComponent>().toList();
  }

  /// Clear all components from the world
  Future<void> clearWorld() async {
    appLog.fine('Clearing world');
    
    // Reset all resetable components before removing
    await resetAllComponents();
    
    // Remove all children
    removeAll(children);
    _currentLevel = null;
    
    appLog.fine('World cleared');
  }

  @override
  Future<void> reset() async {
    appLog.fine('Resetting ShitmanWorld');
    await clearWorld();
  }
}
