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});
}

class CacheServiceImp implements CacheService {
  SharedPreferences preferencesInstance;

  CacheServiceImp({required this.preferencesInstance});

  @override
  Future<DateTime?> getLastTimeUpdatedFromCache() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    if (prefs.containsKey(CacheConstants.lastTimeUpdated)) {
      String? lastTimeUpdated = prefs.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);
  }
}
