import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/passo/memoranda.dart';
import 'package:unit2/sevices/passo/memoranda.dart';

part 'memoranda_event.dart';
part 'memoranda_state.dart';

class MemorandaBloc extends Bloc<MemorandaEvent, MemorandaState> {
  MemorandaBloc() : super(MemorandaLoading()) {
    on<LoadMemoranda>((event, emit) async {
      emit(MemorandaLoading());
      try {
        final response = await MemorandaServices.instance.fetch();
        print('Memoranda bloc');
        print(response.statusCode);
        print(response.body);
        if (response.statusCode == 200) {
          final List result = jsonDecode(response.body)['data'];

          emit(MemorandaLoaded(
              result.map(((e) => Memoranda.fromJson(e))).toList()));
        } else {
          emit(MemorandaErrorState(response.reasonPhrase!));
        }
      } catch (e) {
        emit(MemorandaErrorState(e.toString()));
      }
    });
  }
}
