import '../../../domain/entities/camera_lock.dart';

class LockState {
  /// All known camera locks
  final Map<int, CameraLock> locks;

  /// Whether the coordinator is connected
  final bool coordinatorConnected;

  /// Pending takeover confirmation request (show dialog to user)
  final TakeoverRequest? pendingTakeover;

  /// Last notification message (for snackbar/toast)
  final String? lastNotification;

  /// Error message
  final String? error;

  const LockState({
    this.locks = const {},
    this.coordinatorConnected = false,
    this.pendingTakeover,
    this.lastNotification,
    this.error,
  });

  LockState copyWith({
    Map<int, CameraLock>? locks,
    bool? coordinatorConnected,
    TakeoverRequest? pendingTakeover,
    bool clearPendingTakeover = false,
    String? lastNotification,
    bool clearNotification = false,
    String? error,
    bool clearError = false,
  }) {
    return LockState(
      locks: locks ?? this.locks,
      coordinatorConnected: coordinatorConnected ?? this.coordinatorConnected,
      pendingTakeover:
          clearPendingTakeover ? null : (pendingTakeover ?? this.pendingTakeover),
      lastNotification:
          clearNotification ? null : (lastNotification ?? this.lastNotification),
      error: clearError ? null : (error ?? this.error),
    );
  }

  /// Check if a camera is locked by this keyboard
  bool isCameraLockedByMe(int cameraId, String keyboardId) {
    final lock = locks[cameraId];
    return lock != null &&
        lock.ownerName.toLowerCase() == keyboardId.toLowerCase();
  }

  /// Check if a camera is locked by another keyboard
  bool isCameraLockedByOther(int cameraId, String keyboardId) {
    final lock = locks[cameraId];
    return lock != null &&
        lock.ownerName.toLowerCase() != keyboardId.toLowerCase();
  }

  /// Get the lock for a camera, if any
  CameraLock? getLock(int cameraId) => locks[cameraId];
}

/// Pending takeover request shown as a dialog
class TakeoverRequest {
  final int cameraId;
  final String requestingKeyboard;

  const TakeoverRequest({
    required this.cameraId,
    required this.requestingKeyboard,
  });
}
