import 'dart:async';
import 'package:bloc/bloc.dart';
import 'editor_session_event.dart';
import 'editor_session_state.dart';
import '../../services/file_service.dart';

class EditorSessionBloc extends Bloc<EditorSessionEvent, EditorSessionState> {
  final FileService _fileService;
  Timer? _expiryTimer;

  EditorSessionBloc(this._fileService) : super(EditorSessionInitial()) {
    on<EditorSessionStarted>(_onEditorSessionStarted);
    on<EditorSessionConnected>(_onEditorSessionConnected);
    on<EditorSessionDisconnected>(_onEditorSessionDisconnected);
    on<EditorSessionEnded>(_onEditorSessionEnded);
  }

  void _onEditorSessionStarted(
    EditorSessionStarted event,
    Emitter<EditorSessionState> emit,
  ) async {
    emit(EditorSessionStarting());
    try {
      final session = await _fileService.requestEditorSession(
        event.orgId,
        event.fileId,
      );
      if (!session.readOnly) {
        emit(EditorSessionActive(editUrl: session.editUrl));
      } else {
        emit(EditorSessionReadOnly(viewUrl: session.editUrl));
      }
      if (session.expiresAt.isAfter(DateTime.now())) {
        _expiryTimer = Timer(
          session.expiresAt.difference(DateTime.now()),
          () => emit(EditorSessionExpired()),
        );
      }
    } catch (e) {
      emit(EditorSessionFailed(message: e.toString()));
    }
  }

  void _onEditorSessionConnected(
    EditorSessionConnected event,
    Emitter<EditorSessionState> emit,
  ) {
    // Handle connection if needed
  }

  void _onEditorSessionDisconnected(
    EditorSessionDisconnected event,
    Emitter<EditorSessionState> emit,
  ) {
    // Handle disconnection if needed
  }

  void _onEditorSessionEnded(
    EditorSessionEnded event,
    Emitter<EditorSessionState> emit,
  ) {
    _expiryTimer?.cancel();
    emit(EditorSessionInitial());
  }
}
