import 'dart:async';

import 'package:logging/logging.dart';
import 'package:result_monad/result_monad.dart';

import 'globals.dart';
import 'models/auth/profile.dart';
import 'services/auth_service.dart';
import 'services/connections_manager.dart';
import 'services/persistent_info_service.dart';
import 'services/setting_service.dart';
import 'utils/active_profile_selector.dart';

const _connectionsRefreshInterval = Duration(hours: 12);
const _timerRefresh = Duration(minutes: 1);

final _logger = Logger('UpdateTimer');

void setupUpdateTimers() {
  Timer.periodic(_timerRefresh, (_) async {
    final service = getIt<AccountsService>();
    if (!service.loggedIn) {
      _logger
          .info('Trying to do update when no logged in accounts. Skipping...');
      return;
    }
    executeUpdatesForProfile(getIt<AccountsService>().currentProfile);
  });
}

Future<void> executeUpdatesForProfile(Profile profile) async {
  final lowBandwidthMode = getIt<SettingsService>().lowBandwidthMode;

  if (lowBandwidthMode) {
    return;
  }

  if (getIt<AccountsService>().currentProfile != profile) {
    return;
  }

  await getIt<ActiveProfileSelector<PersistentInfoService>>()
      .getForProfile(profile)
      .withResultAsync((info) async {
    final dt = DateTime.now().difference(info.lastMyConnectionsUpdate);
    _logger.finer('Time since last update for ${profile.id}: $dt');
    if (dt >= _connectionsRefreshInterval) {
      await getIt<ActiveProfileSelector<ConnectionsManager>>()
          .getForProfile(profile)
          .withResultAsync((m) async => await m.updateAllContacts(true))
          .withError((error) {
        _logger.severe('Error running connections update: $error');
      });
    }
  });
}
