using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace QCRPG.Framework;

public class Configuration
{
	public struct Item
	{
		[XmlAttribute(AttributeName = "Name")]
		public string name;

		[XmlElement(ElementName = "Value")]
		public object value;

		public Item(string name, object value)
		{
			this.name = name;
			this.value = value;
		}
	}

	[XmlAttribute(AttributeName = "Name")]
	public string name;

	[XmlElement(ElementName = "Item")]
	public List<Item> itemList = new List<Item>();

	public void SetBool(string name, bool b)
	{
		SetItem(name, b);
	}

	public void SetByte(string name, byte b)
	{
		SetItem(name, b);
	}

	public void SetDouble(string name, double d)
	{
		SetItem(name, d);
	}

	public void SetInt(string name, int i)
	{
		SetItem(name, i);
	}

	public void SetLong(string name, long l)
	{
		SetItem(name, l);
	}

	public void SetShort(string name, short s)
	{
		SetItem(name, s);
	}

	public void SetString(string name, string s)
	{
		SetItem(name, s);
	}

	public void SetUint(string name, uint u)
	{
		SetItem(name, u);
	}

	public void SetUlong(string name, ulong ul)
	{
		SetItem(name, ul);
	}

	public void SetUshort(string name, ushort us)
	{
		SetItem(name, us);
	}

	public bool GetBool(string name, bool defaultValue)
	{
		return (bool)GetItem(name, typeof(bool), defaultValue);
	}

	public byte GetByte(string name, byte defaultValue)
	{
		return (byte)GetItem(name, typeof(byte), defaultValue);
	}

	public double GetDouble(string name, double defaultValue)
	{
		return (double)GetItem(name, typeof(double), defaultValue);
	}

	public int GetInt(string name, int defaultValue)
	{
		return (int)GetItem(name, typeof(int), defaultValue);
	}

	public long GetLong(string name, long defaultValue)
	{
		return (long)GetItem(name, typeof(long), defaultValue);
	}

	public short GetShort(string name, short defaultValue)
	{
		return (short)GetItem(name, typeof(short), defaultValue);
	}

	public string GetString(string name, string defaultValue)
	{
		return (string)GetItem(name, typeof(string), defaultValue);
	}

	public uint GetUint(string name, uint defaultValue)
	{
		return (uint)GetItem(name, typeof(uint), defaultValue);
	}

	public ulong GetUlong(string name, ulong defaultValue)
	{
		return (ulong)GetItem(name, typeof(ulong), defaultValue);
	}

	public ushort GetUshort(string name, ushort defaultValue)
	{
		return (ushort)GetItem(name, typeof(ushort), defaultValue);
	}

	private void SetItem(string name, object value)
	{
		for (int i = 0; i < itemList.Count; i++)
		{
			if (itemList[i].name == name)
			{
				itemList.RemoveAt(i);
				itemList.Add(new Item(name, value));
				return;
			}
		}
		itemList.Add(new Item(name, value));
	}

	private object GetItem(string name, Type t, object defaultValue)
	{
		foreach (Item item in itemList)
		{
			if (item.name == name)
			{
				if (item.value.GetType() == t)
				{
					return item.value;
				}
				return defaultValue;
			}
		}
		return defaultValue;
	}
}
