import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:system_clock/system_clock.dart';
import 'user_profile.dart';
export 'user_profile.dart';

class AppService extends GetxService{
  final userProfile = UserProfile();
  static AppService get to => Get.find();
  late String appVersion;
  final _serverTime = _ServerTime();
  DateTime get now=>_serverTime.now();

  Future<AppService> init()async{
    await GetStorage.init();
    final packageInfo = await PackageInfo.fromPlatform();
    appVersion = packageInfo.version;
    return this;
  }

  correctByServerNow(DateTime serverNow)=>_serverTime.correctByServerNow(serverNow);
}



class _ServerTime{
  Duration? _systemOpenTimeWhenRcvServerTime;
  DateTime? _serverTime;

  correctByServerNow(DateTime serverNow){
    _systemOpenTimeWhenRcvServerTime = SystemClock.elapsedRealtime();
    _serverTime = serverNow;
  }

  DateTime now(){
    if(_systemOpenTimeWhenRcvServerTime==null){
      return DateTime.now();
    }
    return _serverTime!.add(SystemClock.elapsedRealtime() - _systemOpenTimeWhenRcvServerTime!);
  }
}