﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Text.RegularExpressions;

namespace Automation.E2E.Configuration
{
    /// <summary>
    /// Converts an Enum to and from its name string value
    /// - customized behavior when reading from JSON
    /// - empty value is converted to Default
    /// - white spaces are ignored
    /// - case-insensitive
    /// </summary>
    public class CustomStringEnumConverter : StringEnumConverter
    {
        /// <summary>
        /// Reads the JSON representation of the object
        /// </summary>
        /// <param name="reader">The JsonReader to read from</param>
        /// <param name="objectType">Type of the object</param>
        /// <param name="existingValue">The existing value of object being read</param>
        /// <param name="serializer">The calling serializer</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string text = reader.Value.ToString();
            if (string.IsNullOrEmpty(text)) text = "Default"; // if empty set to Default
            text = Regex.Replace(text, @"\s+", ""); // remove all white spaces
            return Enum.Parse(objectType, text, true); // convert to enum ignoreCase
        }
    }
}
