import 'dart:async';
import 'dart:convert';
import 'dart:io';
import '../interfaces/i_idle_monitor.dart';

class IdleMonitor implements IIdleMonitor {
  static const String _idleLightStartKey = 'IDLE_LIGHT_START';
  static const String _idleDeepStartKey = 'IDLE_DEEP_START';
  static const String _idleEndKey = 'IDLE_END';

  Process? _hypridleProcess;
  final StreamController<IdleStatus> _idleStateController = StreamController<IdleStatus>.broadcast();
  IdleStatus _currentIdleStatus = IdleStatus.active;

  @override
  Stream<IdleStatus> get idleStateStream => _idleStateController.stream;

  @override
  IdleStatus get status => _currentIdleStatus;

  @override
  Future<void> start() async {
    // Create a simple hypridle config for tracking
    final configContent = '''
listener {
    timeout = 20
    on-timeout = echo "$_idleLightStartKey"
    on-resume  = echo "$_idleEndKey"
}

listener {
    timeout = 120
    on-timeout = echo "$_idleDeepStartKey"
    on-resume  = echo "$_idleEndKey"
}
''';

    final configFile = File('/tmp/productivity_hypridle.conf');
    await configFile.writeAsString(configContent);

    // Start active
    _idleStateController.add(IdleStatus.active);

    // Start hypridle with our config
    _hypridleProcess = await Process.start('hypridle', ['-c', configFile.path]);

    _hypridleProcess!.stdout.transform(utf8.decoder).transform(LineSplitter()).listen(_handleHypridleOutput);
  }

  void _handleHypridleOutput(String line) {
    switch (line) {
      case String s when s.contains(_idleLightStartKey):
        _idleStateController.add(IdleStatus.lightIdle);
        _currentIdleStatus = IdleStatus.lightIdle;
        print('User went light idle');
      case String s when s.contains(_idleDeepStartKey):
        _idleStateController.add(IdleStatus.deepIdle);
        _currentIdleStatus = IdleStatus.deepIdle;
        print('User went deep idle');
      case String s when s.contains(_idleEndKey):
        _idleStateController.add(IdleStatus.active);
        _currentIdleStatus = IdleStatus.active;
        print('User went active');
    }
  }

  @override
  void stop() {
    _hypridleProcess?.kill();
    _idleStateController.close();
  }
}
