using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Xml;

namespace XmlForDB;

public abstract class SimpleOptions
{
	public abstract Dictionary<string, string> ValueLookup { get; }

	public abstract Dictionary<string, string> NewValueLookup { get; }

	public virtual void AddToNewLookUpList(string value)
	{
		string key = value.Trim();
		if (!NewValueLookup.ContainsKey(key))
		{
			NewValueLookup.Add(key, Constants.NEWEMPTYVALUE);
		}
	}

	public virtual bool CheckCondition(string value)
	{
		return true;
	}

	public virtual void ClearNewValues()
	{
		NewValueLookup.Clear();
	}

	public virtual string GetIDFromLookup(string key)
	{
		string value = string.Empty;
		if (ValueLookup.TryGetValue(key.Trim(), out value))
		{
			return value;
		}
		return string.Empty;
	}

	public virtual string GetNewValues()
	{
		StringWriter stringWriter = new StringWriter();
		try
		{
			stringWriter.NewLine = string.Empty;
			XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
			xmlWriterSettings.OmitXmlDeclaration = true;
			using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
			{
				xmlWriter.WriteStartDocument();
				xmlWriter.WriteStartElement(Constants.ROOT_ELEMENTNAME);
				foreach (KeyValuePair<string, string> item in NewValueLookup)
				{
					xmlWriter.WriteStartElement(Constants.NEWVALUE_ELEMENTNAME);
					xmlWriter.WriteStartElement(Constants.NEWLOOKUPVALUE_ELEMENTNAME);
					xmlWriter.WriteString(item.Key);
					xmlWriter.WriteEndElement();
					xmlWriter.WriteEndElement();
				}
				xmlWriter.WriteEndElement();
				xmlWriter.WriteEndDocument();
			}
			return stringWriter.ToString();
		}
		finally
		{
			stringWriter.Close();
		}
	}

	public virtual void PopulateValues(DataSet ds)
	{
		if (ds == null || ds.Tables.Count <= 0)
		{
			return;
		}
		foreach (DataRow row in ds.Tables[0].Rows)
		{
			if (!ValueLookup.ContainsKey(row[Constants.VALUE].ToString()))
			{
				ValueLookup.Add(row[Constants.VALUE].ToString(), row[Constants.ID].ToString());
			}
		}
	}

	public virtual void ClearLookupValues()
	{
		ValueLookup.Clear();
	}

	public virtual bool LookupHasValues()
	{
		return ValueLookup.Count > 0;
	}

	public virtual int NewValueCount()
	{
		return NewValueLookup.Count;
	}
}
