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

import '../../../domain/analytic/analytic.dart';
import '../../../domain/analytic/repositories/i_analytic_repository.dart';

part 'profit_sharing_loader_event.dart';
part 'profit_sharing_loader_state.dart';
part 'profit_sharing_loader_bloc.freezed.dart';

@injectable
class ProfitSharingLoaderBloc
    extends Bloc<ProfitSharingLoaderEvent, ProfitSharingLoaderState> {
  final IAnalyticRepository _repository;

  ProfitSharingLoaderBloc(this._repository)
    : super(ProfitSharingLoaderState.initial()) {
    on<ProfitSharingLoaderEvent>(_onProfitSharingLoaderEvent);
  }

  Future<void> _onProfitSharingLoaderEvent(
    ProfitSharingLoaderEvent event,
    Emitter<ProfitSharingLoaderState> emit,
  ) {
    return event.map(
      rangeDateChanged: (e) async {
        emit(state.copyWith(dateFrom: e.dateFrom, dateTo: e.dateTo));
      },
      periodTypeChanged: (e) async {
        emit(state.copyWith(periodType: e.periodType));
      },
      fetched: (e) async {
        emit(state.copyWith(isFetching: true, failureOption: none()));

        final result = await _repository.getProfitSharing(
          dateFrom: state.dateFrom,
          dateTo: state.dateTo,
        );

        final newState = result.fold(
          (f) => state.copyWith(failureOption: optionOf(f)),
          (profitSharing) => state.copyWith(profitSharing: profitSharing),
        );

        emit(newState.copyWith(isFetching: false));
      },
    );
  }
}
