import 'dart:async';
import 'dart:convert';

import 'package:krezus/clients/storage/json_storage_client.dart';
import 'package:krezus/repositories/json/models/json.dart';

class JsonRepository {
  String accountFile = 'krezus_main_account.json';

  final JsonStorageClient _storageClient;

  Map<String, Timer> saveTimerMap = {};

  JsonRepository({
    required storageClient,
  }) : _storageClient = storageClient;

  void saveJson(Json json) {
    Timer? saveTimer = saveTimerMap[json.getJsonFileName()];

    if (saveTimer != null) {
      saveTimer.cancel();
    }

    saveTimer = Timer(const Duration(milliseconds: 500), () {
      saveTimerMap.remove(json.getJsonFileName());
      _storageClient.save(json.getJsonFileName(), jsonEncode(json.toJson()));
    });
  }

  Future<T> loadJson<T extends Json>(Json json, JsonFactory<T> jsonFactory) async {
    String jsonString = await _storageClient.load(json.getJsonFileName());

    if (jsonString.isEmpty) {
      return jsonFactory.fromJson({});
    } else {
      return jsonFactory.fromJson(jsonDecode(jsonString));
    }
  }

  deleteJson(Json json) async {
    await _storageClient.delete(json.getJsonFileName());
  }
}
