using System;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework;
using Newtonsoft.Json.Linq;
using StardewModdingAPI.Framework.Exceptions;
namespace StardewModdingAPI.Framework.Serialisation.CrossplatformConverters
{
/// Handles deserialisation of for crossplatform compatibility.
///
/// - Linux/Mac format: { "X": 1, "Y": 2, "Width": 3, "Height": 4 }
/// - Windows format: "{X:1 Y:2 Width:3 Height:4}"
///
internal class RectangleConverter : SimpleReadOnlyConverter
{
/*********
** Protected methods
*********/
/// Read a JSON object.
/// The JSON object to read.
/// The path to the current JSON node.
protected override Rectangle ReadObject(JObject obj, string path)
{
int x = obj.Value(nameof(Rectangle.X));
int y = obj.Value(nameof(Rectangle.Y));
int width = obj.Value(nameof(Rectangle.Width));
int height = obj.Value(nameof(Rectangle.Height));
return new Rectangle(x, y, width, height);
}
/// Read a JSON string.
/// The JSON string value.
/// The path to the current JSON node.
protected override Rectangle ReadString(string str, string path)
{
if (string.IsNullOrWhiteSpace(str))
return Rectangle.Empty;
var match = Regex.Match(str, @"^\{X:(?\d+) Y:(?\d+) Width:(?\d+) Height:(?\d+)\}$");
if (!match.Success)
throw new SParseException($"Can't parse {typeof(Rectangle).Name} from invalid value '{str}' (path: {path}).");
int x = Convert.ToInt32(match.Groups["x"].Value);
int y = Convert.ToInt32(match.Groups["y"].Value);
int width = Convert.ToInt32(match.Groups["width"].Value);
int height = Convert.ToInt32(match.Groups["height"].Value);
return new Rectangle(x, y, width, height);
}
}
}