﻿using System;
using System.Data.Common;
using Core.ORM.DML;

namespace Core.ORM
{
	public abstract class DataContext : IDisposable
	{

		#region Infrastructure

		public enum DatabaseType
		{
			MSSQL
		}

		private readonly string _connectionString;
		private readonly DatabaseType _databaseType;

		protected DataContext(string connectionString, DatabaseType databaseType = DatabaseType.MSSQL)
		{
			_connectionString.MustNotBeEmpty();

			_connectionString = connectionString;
			_databaseType = databaseType;
		}

		protected void GuardDisposition()
		{
			var exception = new ObjectDisposedException(nameof(DataContext));

			_isDisposed.MustBe(false, exception.Message, exception);
		}

		private DbConnection _connection;

		protected DbConnection Connection
		{
			get
			{
				GuardDisposition();

				if(_connection == null)
				{
					switch(_databaseType)
					{
						case DatabaseType.MSSQL:
							_connection = new System.Data.SqlClient.SqlConnection(_connectionString);
							break;
						default:
							throw new NotImplementedException($"There is no support for {_databaseType} database type");
					}
				}

				return _connection;
			}
		}

		private bool _isDisposed;

		public virtual void Dispose()
		{
			GuardDisposition();

			if(_connection != null)
			{
				_connection.Dispose();
				_connection = null;
			}

			GC.SuppressFinalize(this);
			_isDisposed = true;
		}

		#endregion

		#region Fluent Query builder

		public SqlBuilder<T> From<T>()
		{
			return new SqlBuilder<T>();
		}

		#endregion

	}
}
