import 'dart:io';

import 'package:hmg_qline/constants/app_constants.dart';
import 'package:shared_preferences/shared_preferences.dart';

abstract class CacheService {
  Future<DateTime?> getLastTimeUpdatedFromCache();

  Future<void> setLastTimeUpdatedInCache({required String lasTimeUpdated});

  Future<void> setLastTimeLogsCleared({required int lastTimeCleared});

  Future<DateTime?> getLastTimeLogsCleared();
}

class CacheServiceImp implements CacheService {
  SharedPreferences preferencesInstance;

  CacheServiceImp({required this.preferencesInstance});

  @override
  Future<DateTime?> getLastTimeUpdatedFromCache() async {
    if (preferencesInstance.containsKey(CacheConstants.lastTimeUpdated)) {
      String? lastTimeUpdated = preferencesInstance.getString(CacheConstants.lastTimeUpdated);
      DateTime currentLastTimeUpdated = DateTime.fromMillisecondsSinceEpoch(int.parse(lastTimeUpdated!));
      return currentLastTimeUpdated;
    } else {
      return null;
    }
  }

  @override
  Future<void> setLastTimeUpdatedInCache({required String lasTimeUpdated}) async {
    await preferencesInstance.setString(CacheConstants.lastTimeUpdated, lasTimeUpdated);
  }

  @override
  Future<DateTime?> getLastTimeLogsCleared() async {
    if (preferencesInstance.containsKey(CacheConstants.lastTimeUpdated)) {
      String? lastTimeUpdated = preferencesInstance.getString(CacheConstants.lastTimeUpdated);
      DateTime currentLastTimeUpdated = DateTime.fromMillisecondsSinceEpoch(int.parse(lastTimeUpdated!));
      return currentLastTimeUpdated;
    } else {
      return null;
    }
  }

  @override
  Future<void> setLastTimeLogsCleared({required int lastTimeCleared}) async {
    await preferencesInstance.setString(CacheConstants.lastTimeUpdated, lastTimeCleared.toString());
  }
}
