using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using Howest.SchemaDiscovery.DbObjects;
using System.Data.Common;

namespace Howest.SchemaDiscovery
{
	public class DbSchemaDiscoverer
	{
		private DbSchemaProvider _provider = null;
		private string _connectionstring;

		public DbSchemaDiscoverer(ConnectionStringSettings settings)
		{
			_provider = DbSchemaProviderFactory.CreateProvider(settings.ProviderName, false);
			_connectionstring = settings.ConnectionString;
		}

		public string DatabaseName
		{
			get
			{
				using (DbConnection con = _provider.GetFactory().CreateConnection())
				{
					con.ConnectionString = _connectionstring;
					con.Open();

					return con.Database;
				}
			}
		}

		public List<Table> DiscoverTables()
		{
			using (DbConnection con = _provider.GetFactory().CreateConnection())
			{
				con.ConnectionString = _connectionstring;
				con.Open();

				return _provider.GetTables(con);
			}
		}

		public List<View> DiscoverViews()
		{
			using (DbConnection con = _provider.GetFactory().CreateConnection())
			{
				con.ConnectionString = _connectionstring;
				con.Open();

				return _provider.GetViews(con);
			}
		}

		public List<Parameter> DiscoverSqlResultSet(string sql)
		{
			using (DbConnection con = _provider.GetFactory().CreateConnection())
			{
				con.ConnectionString = _connectionstring;
				con.Open();

				return _provider.GetSqlResultSet(con, sql);
			}
		}

		public void RunSqlStatement(string sql)
		{
			using (DbConnection con = _provider.GetFactory().CreateConnection())
			{
				con.ConnectionString = _connectionstring;
				con.Open();
				_provider.RunSqlStatement(con, sql);
			}
		}
	}
}
