import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/outlet/outlet.dart';
import '../../../infrastructure/outlet/datasource/local_data_provider.dart';

part 'selected_outlet_event.dart';
part 'selected_outlet_state.dart';
part 'selected_outlet_bloc.freezed.dart';

@injectable
class SelectedOutletBloc
    extends Bloc<SelectedOutletEvent, SelectedOutletState> {
  final OutletLocalDataProvider _localDataProvider;

  SelectedOutletBloc(this._localDataProvider)
    : super(SelectedOutletState.initial()) {
    on<SelectedOutletEvent>(_onSelectedOutletEvent);
  }

  Future<void> _onSelectedOutletEvent(
    SelectedOutletEvent event,
    Emitter<SelectedOutletState> emit,
  ) {
    return event.map(
      loaded: (e) async {
        final savedId = _localDataProvider.getSelectedOutletId();
        final savedName = _localDataProvider.getSelectedOutletName();

        if (savedId != null && savedName != null) {
          emit(
            state.copyWith(
              selectedOutletId: savedId,
              selectedOutlet: Outlet.empty().copyWith(
                id: savedId,
                name: savedName,
              ),
            ),
          );
        } else {
          emit(state.copyWith(selectedOutletId: savedId));
        }
      },
      selected: (e) async {
        await _localDataProvider.saveSelectedOutletId(e.outlet.id);
        await _localDataProvider.saveSelectedOutletName(e.outlet.name);
        emit(
          state.copyWith(
            selectedOutlet: e.outlet,
            selectedOutletId: e.outlet.id,
          ),
        );
      },
      cleared: (e) async {
        await _localDataProvider.deleteSelectedOutletId();
        emit(SelectedOutletState.initial());
      },
    );
  }
}
