import 'dart:io';

import 'package:aitrainer_app/service/firebase_api.dart';
import 'package:aitrainer_app/util/app_language.dart';
import 'package:aitrainer_app/util/app_localization.dart';
import 'package:aitrainer_app/service/api.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:aitrainer_app/service/package_service.dart';
import 'package:aitrainer_app/util/purchases.dart';
import 'package:devicelocale/devicelocale.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:aitrainer_app/model/cache.dart';

class Session with Logging {
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  late SharedPreferences _sharedPreferences;

  fetchSessionAndNavigate() async {
    log(" -- Session: await prefs..");
    _sharedPreferences = await _prefs;
    print("Platform: " + Platform.localeName);
    Cache().packageInfo = await PackageInfo.fromPlatform();
    if (Cache().firstLoad) {
      log(" -- Session: fetch locale..");
      await AppLanguage().getLocale(_sharedPreferences);
      await AppLocalizations.delegate.load(AppLanguage().appLocal);
      log(" -- Session: fetch token..");
      Cache().setServerAddress(_sharedPreferences);
      Cache().getHardware(_sharedPreferences);
      await _fetchToken(_sharedPreferences);
      await RevenueCatPurchases().initPlatform();
      bool res = await FlutterAppBadger.isAppBadgeSupported();
      if (res == true) {
        FlutterAppBadger.removeBadge();
      }
    }
  }

  Future<void> initDeviceLocale() async {
    List? languages;
    String? currentLocale;

    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      languages = await Devicelocale.preferredLanguages;
      Cache().deviceLanguages = languages;
      log("device langs " + languages.toString());
    } on PlatformException {
      log("Error obtaining preferred languages");
    }
    try {
      currentLocale = await Devicelocale.currentLocale;
      log("Device currentlocale $currentLocale");
    } on PlatformException {
      log("Error obtaining current locale");
    }
  }

  /*
    Auth flow of the user, see auth.dart
   */
  _fetchToken(SharedPreferences prefs) async {
    var responseJson = await APIClient().authenticateUser(Cache.username, Cache.password);
    int? customerId = 0;
    log("--- Lang: " + AppLanguage().appLocal.toString());
    if (responseJson['error'] != null) {
      log("************** Here big error - no authentication");
    } else if (responseJson['token'] != null) {
      prefs.setString(Cache.authTokenKey, responseJson['token']);
      Cache().authToken = responseJson['token'];
      Cache().firebaseUid = prefs.getString(Cache.firebaseUidKey);
      await PackageApi().getPackage();

      if (prefs.get(Cache.customerIdKey) == null) {
        log("************** Registration");
        // registration
        prefs.setBool(Cache.isRegisteredKey, true);
        Cache().startPage = "registration";
      } else {
        DateTime now = DateTime.now();
        String? lastStore = prefs.getString(Cache.lastStoreDateKey);
        if (lastStore != null) {
          DateTime lastStoreDate = DateTime.parse(lastStore);
          DateTime minStoreDate = now.add(Duration(days: -10));

          if (lastStoreDate.difference(minStoreDate) > Duration(days: 10) ||
              prefs.get(Cache.isLoggedInKey) == null ||
              prefs.get(Cache.isLoggedInKey) == false) {
            log("*************  Login");
            Cache().startPage = "login";
          } else {
            if (Cache().firebaseUid == null) {
              log("*************  firebaseUid is null, Login");
              Cache().startPage = "login";
            } else {
              // get API customer
              customerId = prefs.getInt(Cache.customerIdKey);
              if (customerId == null) {
                customerId = 0;
              }
              Cache().startPage = "home";
              log("Customer in the preferences $customerId");
              await Cache().initCustomer(customerId);
            }
          }
        }
        log("--- Session finished");
      }
    }
  }
}