import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hub/features/backend/index.dart';
import 'package:hub/features/local/index.dart';
import 'package:hub/features/menu/index.dart';
import 'package:hub/features/module/index.dart';

class MenuEvent {}

class MenuState {
  final List<MenuItem?> menuEntries;
  final bool isGrid;

  MenuState({this.menuEntries = const [], this.isGrid = false});

  MenuState copyWith({List<MenuItem?>? menuEntries, bool? isGrid}) {
    return MenuState(
      menuEntries: menuEntries ?? this.menuEntries,
      isGrid: isGrid ?? this.isGrid,
    );
  }
}

class MenuBloc extends Bloc<MenuEvent, MenuState> {
  final MenuView style;
  final EnumMenuItem item;
  final List<MenuEntry> entries;
  late StreamSubscription<bool> _completer;

  MenuBloc({required this.style, required this.item, required this.entries})
      : super(MenuState()) {
    on<MenuEvent>(_onMenuEvent);
    _completer = LocalsRepositoryImpl.license.stream.listen((v) {
      add(MenuEvent());
    });
  }

  Future<void> _onMenuEvent(MenuEvent event, Emitter<MenuState> emit) async {
    await LicenseRemoteDataSourceImpl(PhpGroup()).waitForSaveCompletion();

    final List<MenuItem?> newEntries =
        await MenuRepositoryImpl().entries2Items(entries, item);
    emit(state.copyWith(menuEntries: newEntries));
  }

  @override
  Future<void> close() {
    _completer.cancel();
    return super.close();
  }
}
