import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/service/tracking_service.dart';
import 'package:aitrainer_app/util/enums.dart';
import 'package:aitrainer_app/model/tracking.dart' as model;
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:posthog_flutter/posthog_flutter.dart';
import 'package:matomo_tracker/matomo_tracker.dart';
import 'package:flutter/foundation.dart';

class Track with Logging {
  static final Track _singleton = Track._internal();
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  factory Track() {
    return _singleton;
  }

  Track._internal();

  void track(TrackingEvent event, {String eventValue = ""}) {
    model.Tracking tracking = model.Tracking();
    tracking.customerId = Cache().userLoggedIn == null ? 0 : Cache().userLoggedIn!.customerId!;
    if (kReleaseMode) {
      tracking.event = event.enumToString();
      if (eventValue.isNotEmpty) {
        tracking.eventValue = eventValue;
      }
      tracking.dateAdd = DateTime.now();

      TrackingApi().saveTracking(tracking);

      FirebaseMessaging.instance.subscribeToTopic(event.enumToString());
      analytics.logEvent(name: event.enumToString(), parameters: {"value": eventValue});

      if (eventValue.isNotEmpty) {
        MatomoTracker.instance.trackEvent(eventCategory: "wt", action: event.enumToString(), eventName: eventValue);
      } else {
        MatomoTracker.instance.trackEvent(eventCategory: "wt", action: event.enumToString());
      }
      Posthog().capture(
        eventName: event.enumToString(),
        properties: {
          'eventValue': eventValue,
          'customer': tracking.customerId,
        },
      );
      
    }

  }
}
