using System;
using System.Data;
using System.Data.SqlClient;

namespace QC.CTDS.DM.DataStructures.PluginDataStructure;

public class DbAutoDescriptorPlugin : AutoDescriptorPlugin
{
	private string serverName;

	private string databaseName;

	private int connectionTimeout = -1;

	private int commandTimeout = -1;

	public string ServerName
	{
		get
		{
			return serverName;
		}
		set
		{
			serverName = value;
		}
	}

	public string DatabaseName
	{
		get
		{
			return databaseName;
		}
		set
		{
			databaseName = value;
		}
	}

	public int ConnectionTimeout
	{
		get
		{
			return connectionTimeout;
		}
		set
		{
			connectionTimeout = value;
		}
	}

	public int CommandTimeout
	{
		get
		{
			return commandTimeout;
		}
		set
		{
			commandTimeout = value;
		}
	}

	public DbAutoDescriptorPlugin(string serverName, string databaseName)
	{
		ServerName = serverName;
		DatabaseName = databaseName;
	}

	protected DataTable GetData(string query)
	{
		try
		{
			using SqlConnection sqlConnection = new SqlConnection(getConnectionString());
			sqlConnection.Open();
			SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
			if (commandTimeout > 0)
			{
				sqlCommand.CommandTimeout = commandTimeout;
			}
			DataTable dataTable = new DataTable();
			dataTable.Load(sqlCommand.ExecuteReader());
			sqlConnection.Close();
			return dataTable;
		}
		catch (Exception ex)
		{
			WriteLog("Error grabbing auto data: " + ex.Message, LogType.Error);
			return null;
		}
	}

	private string getConnectionString()
	{
		string text = $"Data Source={serverName};Initial Catalog={databaseName};Integrated Security=True";
		if (connectionTimeout > 0)
		{
			text = text + ";Connection Timeout=" + connectionTimeout;
		}
		return text;
	}

	protected bool TestConnection()
	{
		SqlConnection sqlConnection = null;
		try
		{
			sqlConnection = new SqlConnection(getConnectionString());
			sqlConnection.Open();
		}
		catch (Exception)
		{
			sqlConnection?.Close();
			return false;
		}
		finally
		{
			sqlConnection?.Close();
		}
		return true;
	}
}
