import 'dart:convert';
import 'package:fis_common/logger/logger.dart';
import 'package:vitalapp/architecture/storage/text_storage.dart';

import 'interfaces/application.dart';

class ApplicationManager implements IApplicationManager {
  final _storage = TextStorage(fileName: "local.properties");
  Map<String, dynamic>? _cache;

  @override
  Future<Map<String, dynamic>> getProperties() async {
    if (_cache == null) {
      try {
        final jsonText = await _storage.read();
        if (jsonText != null) {
          _cache = jsonDecode(jsonText);
        } else {
          _cache = {};
        }
      } catch (e) {
        logger.e("ApplicationManager getProperties error", e);
      }
    }

    return _cache!;
  }

  @override
  Future<dynamic> getProperty(String key) async {
    final map = await getProperties();
    return map[key];
  }

  @override
  Future<void> setProperty(String key, dynamic value) async {
    try {
      final map = await getProperties();
      map[key] = value;
      final jsonText = jsonEncode(map);
      await _storage.save(jsonText);
    } catch (e) {
      logger.e("ApplicationManager setProperty-$key error", e);
    }
  }

  @override
  Future<void> setProperties(Map<String, dynamic> data) async {
    try {
      final map = await getProperties();
      for (var key in data.keys) {
        map[key] = data[key];
      }
      final jsonText = jsonEncode(map);
      await _storage.save(jsonText);
    } catch (e) {
      logger.e("ApplicationManager setProperties error", e);
    }
  }
}
