
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

import 'info_module.dart';

class SyncedTimeModule extends InfoModule  {

  int timeOffset = -1;
  DateTime lastUpdate = DateTime.now().add(const Duration(seconds: -15));

  SyncedTimeModule() {
    refreshTimer();
  }

  Timer refreshTimer() => Timer.periodic(const Duration(seconds: 10), (timer) async {

    try {
      var res = await http.get(Uri.parse('http://worldtimeapi.org/api/timezone/Europe/London'));
      if (res.statusCode == 200) {
        var json = jsonDecode(res.body);
        DateTime time = DateTime.parse(json['datetime']);
        timeOffset = time.millisecondsSinceEpoch - DateTime.now().millisecondsSinceEpoch;
        lastUpdate = DateTime.now();
        print("Time offset: $timeOffset");
      }
    } catch (e) {
      print("Failed to get time from worldtimeapi.org");
    }
  });

  DateTime Now() {
    if (timeOffset == -1) {
      return DateTime.now();
    }
    return DateTime.now().add(Duration(milliseconds: timeOffset));
  }
}