using System;
using System.IO;
using System.Linq;
using BepInEx.Logging;
namespace BepInEx.Configuration
{
	/// 
	/// Container for a single setting of a . 
	/// Each config entry is linked to one config file.
	/// 
	public abstract class ConfigEntryBase
	{
		/// 
		/// Types of defaultValue and definition.AcceptableValues have to be the same as settingType.
		/// 
		internal ConfigEntryBase(ConfigFile configFile, ConfigDefinition definition, Type settingType, object defaultValue)
		{
			ConfigFile = configFile ?? throw new ArgumentNullException(nameof(configFile));
			Definition = definition ?? throw new ArgumentNullException(nameof(definition));
			SettingType = settingType ?? throw new ArgumentNullException(nameof(settingType));
			// Free type check
			BoxedValue = defaultValue;
			DefaultValue = defaultValue;
		}
		/// 
		/// Config file this entry is a part of.
		/// 
		public ConfigFile ConfigFile { get; }
		/// 
		/// Category and name of this setting. Used as a unique key for identification within a .
		/// 
		public ConfigDefinition Definition { get; }
		/// 
		/// Description / metadata of this setting.
		/// 
		public ConfigDescription Description { get; private set; }
		/// 
		/// Type of the  that this setting holds.
		/// 
		public Type SettingType { get; }
		/// 
		/// Default value of this setting (set only if the setting was not changed before).
		/// 
		public object DefaultValue { get; }
		/// 
		/// Get or set the value of the setting.
		/// 
		public abstract object BoxedValue { get; set; }
		/// 
		/// Get the serialized representation of the value.
		/// 
		public string GetSerializedValue()
		{
			return TomlTypeConverter.ConvertToString(BoxedValue, SettingType);
		}
		/// 
		/// Set the value by using its serialized form.
		/// 
		public void SetSerializedValue(string value)
		{
			try
			{
				var newValue = TomlTypeConverter.ConvertToValue(value, SettingType);
				BoxedValue = newValue;
			}
			catch (Exception e)
			{
				Logging.Logger.Log(LogLevel.Warning, $"Config value of setting \"{Definition}\" could not be parsed and will be ignored. Reason: {e.Message}; Value: {value}");
			}
		}
		internal void SetDescription(ConfigDescription configDescription)
		{
			if (configDescription == null) throw new ArgumentNullException(nameof(configDescription));
			if (configDescription.AcceptableValues != null && !SettingType.IsAssignableFrom(configDescription.AcceptableValues.ValueType))
				throw new ArgumentException("configDescription.AcceptableValues is for a different type than the type of this setting");
			Description = configDescription;
			// Automatically calls ClampValue in case it changed
			BoxedValue = BoxedValue;
		}
		/// 
		/// If necessary, clamp the value to acceptable value range. T has to be equal to settingType.
		/// 
		protected T ClampValue(T value)
		{
			if (Description?.AcceptableValues != null)
				return (T)Description.AcceptableValues.Clamp(value);
			return value;
		}
		/// 
		/// Trigger setting changed event.
		/// 
		protected void OnSettingChanged(object sender)
		{
			ConfigFile.OnSettingChanged(sender, this);
		}
		/// 
		/// Write a description of this setting using all available metadata.
		/// 
		public void WriteDescription(StreamWriter writer)
		{
			bool hasDescription = Description != null;
			if (hasDescription)
				writer.WriteLine(Description.ToSerializedString());
			writer.WriteLine("# Setting type: " + SettingType.Name);
			writer.WriteLine("# Default value: " + DefaultValue);
			if (hasDescription && Description.AcceptableValues != null)
			{
				writer.WriteLine(Description.AcceptableValues.ToSerializedString());
			}
			else if (SettingType.IsEnum)
			{
				writer.WriteLine("# Acceptable values: " + string.Join(", ", Enum.GetNames(SettingType)));
				if (SettingType.GetCustomAttributes(typeof(FlagsAttribute), true).Any())
					writer.WriteLine("# Multiple values can be set at the same time by separating them with , (e.g. Debug, Warning)");
			}
		}
	}
}