import 'package:flutter/foundation.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../../../../api/marianumconnect/queries/get_breakers/get_breakers_response.dart';
import '../../../infrastructure/utility_widgets/loadable_hydrated_bloc/loadable_hydrated_bloc.dart';
import '../../../infrastructure/utility_widgets/loadable_hydrated_bloc/loadable_hydrated_bloc_event.dart';
import '../repository/breaker_repository.dart';
import 'breaker_event.dart';
import 'breaker_state.dart';

class BreakerBloc
    extends
        LoadableHydratedBloc<BreakerEvent, BreakerState, BreakerRepository> {
  PackageInfo? _packageInfo;

  @override
  BreakerRepository repository() => BreakerRepository();

  @override
  BreakerState fromNothing() => const BreakerState();

  @override
  BreakerState fromStorage(Map<String, dynamic> json) =>
      BreakerState.fromJson(json);

  @override
  Map<String, dynamic>? toStorage(BreakerState state) => state.toJson();

  @override
  Future<void> gatherData() async {
    _packageInfo ??= await PackageInfo.fromPlatform();
    final response = await repo.data.getBreakers();
    add(DataGathered((s) => s.copyWith(response: response)));
  }

  void refresh() => fetch();

  String? isBlocked(BreakerArea? type) {
    if (kDebugMode) return null;
    final response = innerState?.response;
    if (response == null || _packageInfo == null) return null;

    final selfBuild = int.tryParse(_packageInfo!.buildNumber) ?? 0;
    for (final rule in response.rules) {
      if (!rule.areas.contains(type)) continue;
      if (rule.maxBuild == null || selfBuild <= rule.maxBuild!) {
        return rule.message;
      }
    }
    return null;
  }
}
