import 'dart:isolate';

import 'package:aves/app_flavor.dart';
import 'package:aves/services/common/services.dart';
import 'package:aves/widgets/aves_app.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:leak_tracker/leak_tracker.dart';

void mainCommon(AppFlavor flavor, {Map? debugIntentData}) {
  initPlatformServices();

  Isolate.current.addErrorListener(
    RawReceivePort((pair) {
      final errorAndStacktrace = pair as List;
      final error = errorAndStacktrace[0] as String;
      final stackTraceString = errorAndStacktrace[1] as String?;
      final stackTrace = stackTraceString != null ? StackTrace.fromString(stackTraceString) : null;
      reportService.recordError(error, stackTrace);
    }).sendPort,
  );

  LeakTracking.start();
  FlutterMemoryAllocations.instance.addListener(
    (event) => LeakTracking.dispatchObjectEvent(event.toMap()),
  );

  runApp(
    AvesApp(
      flavor: flavor,
      debugIntentData: debugIntentData,
    ),
  );
}
