import 'package:be_happy/core/result.dart';
import 'package:be_happy/domain/entities/subscription.dart';
import 'package:be_happy/domain/usecase/activate_subscription_usecase.dart';
import 'package:be_happy/domain/usecase/get_subscription_by_id_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../event/subscription_details_event.dart';
import '../state/susbcription_details_state.dart';

class SubscriptionDetailsBloc extends Bloc<SubscriptionDetailsEvent, SubscriptionDetailsState> {
  final GetSubscriptionByIdUsecase getSubscriptionByIdUsecase;
  final ActivateSubscriptionUsecase activateSubscriptionUsecase;

  SubscriptionDetailsBloc(this.getSubscriptionByIdUsecase,
      this.activateSubscriptionUsecase) : super(DetailsLoading()) {
    on<LoadDetailsEvent>((event, emit) async {
      emit(DetailsLoading());
      try {

        final result = await getSubscriptionByIdUsecase(event.subscriptionId);

        switch (result) {

          case Success<Subscription>():
            final sub = result.data;

            if (sub == null) return;

            emit(DetailsContentState(
              subscription: sub,
              selectedPeriod: sub.options.first,
            ));
          case Failure<Subscription>():
            emit(DetailsError("Ошибка при запросе данных"));

        }


      } catch (e) {
        emit(DetailsError("Не удалось загрузить данные"));
      }
    });

    on<SelectPeriodEvent>((event, emit) {
      if (state is DetailsContentState) {
        emit((state as DetailsContentState).copyWith(selectedPeriod: event.period));
      }
    });

    on<ToggleAgreementEvent>((event, emit) {
      if (state is DetailsContentState) {
        emit((state as DetailsContentState).copyWith(isAgreed: event.value));
      }
    });

    on<ActivateSubscriptionPressed>((event, emit) {
      switch(state) {
        case DetailsContentState contentState:
          activateSubscriptionUsecase(contentState.selectedPeriod.id);
          break;
        default:
          break;
      }
    });
  }
}