import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/bloc/app_events.dart';
import 'package:hl_lieferservice/bloc/app_states.dart';
import 'package:hl_lieferservice/main.dart';
import 'package:hl_lieferservice/repository/config.dart';

import '../services/erpframe.dart';

class AppBloc extends Bloc<AppEvents, AppState> {
  AppBloc() : super(AppInitial()) {
    on<AppLoadConfig>(_loadConfig);
  }

  Future<void> _loadConfig(AppLoadConfig event, Emitter<AppState> emit) async {
    emit(AppConfigLoading());
    try {
      final repository = ConfigurationRepository(path: event.path);
      final configuration = LocalDocuFrameConfiguration.fromJson(
        json.decode(await rootBundle.loadString("assets/${event.path}")),
      );

      repository.setDocuFrameConfiguration(configuration);

      var config = await repository.getDocuFrameConfiguration();
      locator.registerSingleton<LocalDocuFrameConfiguration>(config);

      emit(
        AppConfigLoaded(config: config),
      );
    } catch (e) {
      emit(
        AppConfigLoadingFailed(
          message: "Fehler beim Laden der Konfigurationsdatei.",
        ),
      );
    }
  }
}
