import 'package:aitrainer_app/localization/app_language.dart';
import 'package:aitrainer_app/localization/app_localization.dart';
import 'package:aitrainer_app/repository/exercise_repository.dart';
import 'package:aitrainer_app/service/api.dart';
import 'package:aitrainer_app/service/customer_service.dart';
import 'package:aitrainer_app/service/exercise_tree_service.dart';
import 'package:aitrainer_app/service/exercisetype_service.dart';
import 'package:aitrainer_app/service/firebase_api.dart';
import 'package:aitrainer_app/service/property_service.dart';
import 'package:devicelocale/devicelocale.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:aitrainer_app/model/cache.dart';
import 'package:firebase_core/firebase_core.dart';

//import '../push_notifications.dart';

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

  SharedPreferences _sharedPreferences;

  fetchSessionAndNavigate() async {
    print(" -- Session: await prefs..");
    _sharedPreferences = await _prefs;

    if (Cache().firstLoad) {
      print(" -- Session: fetch locale..");
      await AppLanguage().getLocale(_sharedPreferences);
      await AppLocalizations.delegate.load(AppLanguage().appLocal);
      print(" -- Session: fetch token..");
      await _fetchToken(_sharedPreferences);
      print(" -- FireBase init..");
      await FirebaseApi().initializeFlutterFire();
      //initDeviceLocale();

      // Create the initialization Future outside of `build`:

      //  PushNotificationsManager().init();
    }
  }

  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;
      print("device langs " + languages.toString());
    } on PlatformException {
      print("Error obtaining preferred languages");
    }
    try {
      currentLocale = await Devicelocale.currentLocale;
      print("Device currentlocale " + currentLocale);
    } on PlatformException {
      print("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;
    print("--- Lang: " + AppLanguage().appLocal.toString());
    if (responseJson['error'] != null) {
      print("************** Here big error - no authentication");
    } else if (responseJson['token'] != null) {
      prefs.setString(Cache.authTokenKey, responseJson['token']);
      Cache().authToken = responseJson['token'];
      Cache().firebaseUid = prefs.get(Cache.firebaseUidKey);
      if (prefs.get(Cache.customerIdKey) == null) {
        print("************** Registration");
        // registration
        prefs.setBool(Cache.isRegisteredKey, true);
        Cache().startPage = "registration";
      } else {
        DateTime now = DateTime.now();
        DateTime lastStoreDate = DateTime.parse(prefs.get(Cache.lastStoreDateKey));
        DateTime minStoreDate = now.add(Duration(days: -10));

        if (lastStoreDate == null ||
            lastStoreDate.difference(minStoreDate) > Duration(days: 10) ||
            prefs.get(Cache.isLoggedInKey) == null ||
            prefs.get(Cache.isLoggedInKey) == false) {
          print("*************  Login");
          Cache().startPage = "login";
        } else {
          // only
          if (Cache().firebaseUid == null) {
            print("*************  firebaseUid is null, Login");
            Cache().startPage = "login";
          } else {
            // get API customer
            customerId = prefs.getInt(Cache.customerIdKey);
            await PropertyApi().getProperties();
            await CustomerApi().getCustomer(customerId);
            Cache().startPage = "home";
          }
        }

        await ExerciseTypeApi().getExerciseTypes();
        await ExerciseTreeApi().getExerciseTree();
        if (customerId > 0) {
          ExerciseRepository exerciseRepository = ExerciseRepository();
          await exerciseRepository.getExercisesByCustomer(customerId);
        }
        print("--- Session finished");
      }
    }
  }
}