import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/analytic_remote_datasource.dart';
import 'package:enaklo_pos/data/datasources/outlet_local_datasource.dart';
import 'package:enaklo_pos/data/models/response/category_analytic_response_model.dart';
import 'package:enaklo_pos/data/models/response/payment_method_analytic_response_model.dart';
import 'package:enaklo_pos/data/models/response/product_analytic_response_model.dart';
import 'package:enaklo_pos/data/models/response/profit_loss_response_model.dart';
import 'package:enaklo_pos/presentation/home/models/outlet_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'report_event.dart';
part 'report_state.dart';
part 'report_bloc.freezed.dart';

class ReportBloc extends Bloc<ReportEvent, ReportState> {
  final AnalyticRemoteDatasource _datasource;
  ReportBloc(this._datasource) : super(ReportState.initial()) {
    on<_Get>((event, emit) async {
      emit(_Loading());

      final outlet = await OutletLocalDatasource().get();

      final category = await _datasource.getCategory(
          dateFrom: event.startDate, dateTo: event.endDate);

      final product = await _datasource.getProduct(
          dateFrom: event.startDate, dateTo: event.endDate);

      final paymentMethod = await _datasource.getPaymentMethod(
          dateFrom: event.startDate, dateTo: event.endDate);

      final profitLoss = await _datasource.getProfitLoss(
          dateFrom: event.startDate, dateTo: event.endDate);

      if (category.isLeft() ||
          product.isLeft() ||
          paymentMethod.isLeft() ||
          profitLoss.isLeft()) {
        emit(_Error());
      }

      emit(_Loaded(
        outlet,
        category
            .getOrElse(
                () => CategoryAnalyticResponseModel(success: false, data: null))
            .data!,
        profitLoss
            .getOrElse(
                () => ProfitLossResponseModel(success: false, data: null))
            .data,
        paymentMethod
            .getOrElse(() =>
                PaymentMethodAnalyticResponseModel(success: false, data: null))
            .data,
        product
            .getOrElse(
                () => ProductAnalyticResponseModel(success: false, data: null))
            .data,
      ));
    });
  }
}
