import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:laba1/presentation/home_page/bloc/state.dart';

import '../../../data/repositories/potter_repository.dart';
import 'events.dart';

class HomeBloc extends Bloc<HomeEvent, HomeState> {
  final PotterRepository repo;

  HomeBloc(this.repo) : super(const HomeState()) {
    on<HomeLoadDataEvent>(_onLoadData);
  }

  Future<void> _onLoadData(
      HomeLoadDataEvent event, Emitter<HomeState> emit) async {
    if (event.nextPage == null) {
      emit(state.copyWith(isLoading: true));
    } else {
      emit(state.copyWith(isPaginationLoading: true));
    }

    String? error;

    final data = await repo.loadData(
      q: event.search,
      page: event.nextPage ?? 1,
      onError: (e) => error = e,
    );
    data?.nextPage = data?.nextPage ?? (event.nextPage ?? 1);
    if (event.nextPage != null) {
      // Добавляем новые данные, пропуская дубликаты
      if (state.data != null) {
        for (var entity in data?.data ?? []) {
          if (!(state.data!.existingIds.contains(entity.id))) {
            state.data?.data?.add(entity);
            state.data?.existingIds.add(entity.id);
          }
        }
      }
      state.data?.nextPage = data?.nextPage;
      emit(state.copyWith(
        isLoading: false,
        isPaginationLoading: false,
        data: state.data,
        error: error,
      ));
    } else {
      emit(state.copyWith(
        isLoading: false,
        isPaginationLoading: false,
        data: data,
        error: error,
      ));
    }
  }
}
