import 'package:aitrainer_app/localization/app_language.dart';
import 'package:aitrainer_app/service/api.dart';
import 'package:aitrainer_app/service/customer_service.dart';
import 'package:aitrainer_app/service/exercisetype_service.dart';
import 'package:devicelocale/devicelocale.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:aitrainer_app/model/auth.dart';

import '../push_notifications.dart';

class Session  {

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  Auth _auth = Auth();
  SharedPreferences _sharedPreferences;
  final AppLanguage appLanguage = AppLanguage();

  fetchSessionAndNavigate(Function callback ) async {
    _sharedPreferences = await _prefs;


    if ( _auth.firstLoad ) {
      _fetchToken(_sharedPreferences, callback);
      initDeviceLocale();
      appLanguage.fetchLocale();
      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;
      Auth().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, Function callback) async {

    var responseJson = await APIClient.authenticateUser(
        Auth.username,
        Auth.password
    );
    print("--- Lang: " + appLanguage.appLocal.toString());
    if(responseJson['error'] != null) {
      print("************** Here big error - no authentication");
    } else if (responseJson['token'] != null) {
      prefs.setString(Auth.authTokenKey, responseJson['token']);
      Auth auth = Auth();
      auth.authToken = responseJson['token'];
      if (prefs.get(Auth.customerIdKey) == null) {
        print("************** Registration");
        // registration
        //Navigator.of(context).pushNamed('registration');
        prefs.setBool(Auth.isRegisteredKey, true);
      } else {
        DateTime now = DateTime.now();
        DateTime lastStoreDate = DateTime.parse(
            prefs.get(Auth.lastStoreDateKey));
        DateTime minStoreDate = now.add(Duration(days: -10));

        if (lastStoreDate == null ||
            lastStoreDate.difference(minStoreDate) > Duration(days: 10) ||
            prefs.get(Auth.isLoggedInKey) == null ||
            prefs.get(Auth.isLoggedInKey) == false) {
          print("*************  Login");
          //Navigator.of(context).pushNamed('login');

        } else {
          print("************** Store SharedPreferences");
          // get API customer
          await CustomerApi().getCustomer(prefs.getInt(Auth.customerIdKey));
        }

        await ExerciseTypeApi().getExerciseTypes("");
        print("--- Session finished, call callback ");
        callback();

      }
    }
  }
}