import 'package:diplomaticquarterapp/analytics/analytic-events.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Singleton {
  const Singleton(); //Constant constructor

  void hello() {
    print('Hello world');
  }
}

var analytics = FirebaseAnalytics();

class GAnalytics {
  const GAnalytics();
  static GAnalytics shared = const GAnalytics();
  NavObserver navObserver() => NavObserver();
}

// adb shell setprop debug.firebase.analytics.app com.ejada.hmg -> Android
class NavObserver extends RouteObserver<PageRoute<dynamic>> {
  _sendScreenView(PageRoute route) async {
    log(String className) {
      var event = AnalyticEvents.get(className);
      if (event.active != null) {
        analytics
            .setCurrentScreen(
                screenName: event.flutterName(), screenClassOverride: className)
            .catchError(
          (Object error) {
            debugPrint('$FirebaseAnalyticsObserver: $error');
          },
          test: (Object error) {
            return error is PlatformException;
          },
        );
      }
    }

    if (route.settings.name != null &&
        route.settings.name.isNotEmpty &&
        route.settings.name != "null") {
      var class_ = routes[route.settings.name](0);
      if (class_ != null) log(class_.toStringShort());
    } else if (route is FadePage) {
      var class_ = route.page;
      if (class_ != null) log(class_.toStringShort());
    } else if (route is MaterialPageRoute) {
      var class_ = route.builder(null);
      if (class_ != null) log(class_.toStringShort());
    } else {
      print("");
    }
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
    super.didPush(route, previousRoute);
    if (route is PageRoute) {
      _sendScreenView(route);
    }
  }

  @override
  void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute is PageRoute) {
      _sendScreenView(newRoute);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
    super.didPop(route, previousRoute);
    // if (previousRoute is PageRoute && route is PageRoute) {
    //   _sendScreenView(previousRoute);
    // }
  }
}
