import 'dart:convert';
import 'dart:ui';
import 'package:guru_utils/colors/color_utils.dart';
import 'package:guru_utils/log/log.dart';
import 'package:json_annotation/json_annotation.dart';

/// Created by Haoyi on 4/28/21

part "color_convert.dart";

part "list_joined_string_convert.dart";

part "config_map_convert.dart";

const joinedStringConvert = JoinedStringListConvert();
const configStringIntMapStringConvert = ConfigStringIntMapStringConvert();
const IntStringConvert intStringConvert = IntStringConvert();
const BoolStringConvert boolStringConvert = BoolStringConvert();

class IntStringConvert implements JsonConverter<int, String> {
  const IntStringConvert();

  @override
  int fromJson(String? json) {
    if (json == null) {
      return -1;
    }
    try {
      return int.parse(json);
    } catch (error) {
      return -1;
    }
  }

  @override
  String toJson(int? value) {
    return value.toString();
  }
}

class BoolStringConvert implements JsonConverter<bool, String> {
  const BoolStringConvert();

  @override
  bool fromJson(String? json) {
    if (json == null) {
      return false;
    }
    try {
      return json == "true" || json == "ok";
    } catch (error) {
      return false;
    }
  }

  @override
  String toJson(bool? value) {
    return (value != null && value == true) ? "true" : "false";
  }
}
