import 'package:diplomaticquarterapp/analytics/analytic-events.dart';
import 'package:diplomaticquarterapp/analytics/flows/advance_payments.dart';
import 'package:diplomaticquarterapp/analytics/flows/appointments.dart';
import 'package:diplomaticquarterapp/analytics/flows/error_tracking.dart';
import 'package:diplomaticquarterapp/analytics/flows/hamburger_menu.dart';
import 'package:diplomaticquarterapp/analytics/flows/live_care.dart';
import 'package:diplomaticquarterapp/analytics/flows/login_registration.dart';
import 'package:diplomaticquarterapp/analytics/flows/offers_promotions.dart';
import 'package:diplomaticquarterapp/analytics/flows/todo_list.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/uitl/location_util.dart';
import 'package:diplomaticquarterapp/uitl/utils.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';

import 'flows/app_nav.dart';
import 'flows/hmg_services.dart';


typedef GALogger = Function(String name, {Map<String,dynamic> parameters});

var _analytics = FirebaseAnalytics();
_logger(String name, {Map<String,dynamic> parameters}) async {
  if (name != null && name.isNotEmpty) {
    if(name.contains(' '))
      name = name.replaceAll(' ','_');
    
    // To LowerCase
    if(parameters != null && parameters.isNotEmpty)
      parameters = parameters.map((key, value) {
        final key_ = key.toLowerCase();
        var value_ = value;
        if(value is String)
          value_ = value.toLowerCase();
        return MapEntry(key_, value_);
      });

    try{
      _analytics
          .logEvent(name: name.trim().toLowerCase(), parameters: parameters)
          .then((value) {
        debugPrint('SUCCESS: Google analytics event "$name" sent with parameters $parameters');
      }).catchError((error) {
        debugPrint('ERROR: Google analytics event "$name" sent failed');
      });
    }catch(e){
      print(e);
    }
  }
}


class GAnalytics {
  static String TREATMENT_TYPE;
  static String APPOINTMENT_DETAIL_FLOW_TYPE;
  static String PAYMENT_TYPE;

  setUser(AuthenticatedUser user){
    if(user != null){
      _analytics.setUserProperty(name: 'user_country', value: user.iSOCountryID);
      _analytics.setUserProperty(name: 'user_language', value: user.preferredLanguage == '1' ? 'arabic' : 'english');
      _analytics.setUserProperty(name: 'userid', value: Utils.generateMd5Hash(user.emailAddress));
      _analytics.setUserProperty(name: 'login_status', value: 'loggedin');
    }else{
      _analytics.setUserProperty(name: 'login_status', value: 'guest');
    }
  }
  
  NavObserver navObserver() => NavObserver();
  final  hamburgerMenu = HamburgerMenu(_logger);
  final  bottomTabNavigation = AppNav(_logger);
  final  hmgServices = HMGServices(_logger);
  final  loginRegistration = LoginRegistration(_logger);
  final  appointment = Appointment(_logger);
  final  liveCare = LiveCare(_logger);
  final  todoList = TodoList(_logger);
  final  advancePayments = AdvancePayments(_logger);
  final  offerPackages = OfferAndPromotion(_logger);
  final  errorTracking = ErrorTracking(_logger);
}



// 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) {
            print('$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);
    // }
  }
}
