import 'dart:convert';

import 'package:{{#snakeCase}}{{project_name}}{{/snakeCase}}/data/models/integer_model.dart';
import 'package:{{#snakeCase}}{{project_name}}{{/snakeCase}}/domain/data_sources/local/counter_data_source.dart';
import 'package:{{#snakeCase}}{{project_name}}{{/snakeCase}}/domain/entities/integer.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';

class CounterDataSourceImpl extends CounterDataSource {
  // Simulate external data processing
  String actual = '{"value": 0}';

  @override
  Future<Integer> decrement(Integer value) async {
    final current =
        IntegerModel.fromJson(json.decode(actual) as Map<String, Object?>);

    final newValue = current.value - value.value;
    if (newValue < 0) {
      throw ClientException("Counter can't be negative!");
    }

    final newInteger = IntegerModel(value: newValue);
    actual = jsonEncode(newInteger.toJson());

    return newInteger;
  }

  @override
  Future<Integer> increment(Integer value) async {
    final current =
        IntegerModel.fromJson(json.decode(actual) as Map<String, Object?>);

    final newValue = current.value + value.value;
    if (newValue < 0) {
      throw ClientException("Counter can't be negative!");
    }

    final newInteger = IntegerModel(value: newValue);
    actual = jsonEncode(newInteger.toJson());

    return newInteger;
  }

  @override
  Future<Integer> getCurrent() async {
    final current =
        IntegerModel.fromJson(json.decode(actual) as Map<String, Object?>);

    return current;
  }

  @override
  Future<Integer> reset() async {
    const newInteger = IntegerModel(value: 0);
    actual = jsonEncode(newInteger.toJson());

    return newInteger;
  }
}
