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

const _messageLength = 100;

class AppBlocObserver extends BlocObserver {
  AppBlocObserver({
    this.printEvent = true,
    this.printError = true,
    this.printTransition = false,
    this.printChange = true,
    this.fullPrint = false,
  });

  final bool printEvent;
  final bool printError;
  final bool printChange;
  final bool printTransition;
  final bool fullPrint;

  String sanitize(Object? object) {
    final message = object.toString();

    return fullPrint
        ? message
        : message.substring(
            0,
            message.length < _messageLength ? message.length : _messageLength,
          );
  }

  @override
  void onEvent(Bloc<dynamic, dynamic> bloc, Object? event) {
    super.onEvent(bloc, event);
    if (printEvent) {
      debugPrint('onEvent:        ${bloc.runtimeType}\n'
          '> event:        ${sanitize(event)}');
    }
  }

  @override
  void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
    if (printError) {
      debugPrint('onError:        ${bloc.runtimeType}\n'
          '> error:        ${sanitize(error)}\n'
          '$stackTrace');
    }
    super.onError(bloc, error, stackTrace);
  }

  @override
  void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) {
    super.onChange(bloc, change);
    if (printChange) {
      debugPrint('onChange:       ${bloc.runtimeType}\n'
          '> currentState: ${sanitize(change.currentState)}\n'
          '> nextState:    ${sanitize(change.nextState)}');
    }
  }

  @override
  void onTransition(
    Bloc<dynamic, dynamic> bloc,
    Transition<dynamic, dynamic> transition,
  ) {
    super.onTransition(bloc, transition);
    if (printTransition) {
      debugPrint('onTransition:   ${bloc.runtimeType}\n'
          '> currentState: ${sanitize(transition.currentState)}\n'
          '> event:        ${sanitize(transition.event)}\n'
          '> nextState:    ${sanitize(transition.nextState)}');
    }
  }
}
