﻿using LibDatabaseCodeMaker.Database.Interface;

namespace LibDatabaseCodeMaker.Database.SqlStatement
{
	/// <summary>
	/// select count(*) 语句
	/// </summary>
	public partial class SelectCountStatement
	{
		/// <summary>
		/// 创建SelectCountStatement对象和Visual Basic对象
		/// </summary>
		/// <returns>SelectCountStatement对象</returns>
		public static SelectCountStatement CreateWithVb()
		{
			SelectCountStatement statement = new SelectCountStatement();
			statement.Target = new VisualBasicLanguage(statement);
			return statement;
		}

		/// <summary>
		/// 创建默认对象
		/// </summary>
		/// <param name="table">表对象</param>
		/// <param name="database">数据库对象</param>
		/// <returns>SelectCountStatement对象</returns>
		public static SelectCountStatement CreateVbMethod(DatabaseTableObject table, DatabaseObject database)
		{
			SelectCountStatement statement = new SelectCountStatement(table, database);

			statement.Target.FunctionName = "SelectCount";
			statement.Target.FunctionComment = string.Format("获取 {0} 表中数据的总数量", table.GetName());
			statement.Target.ReturnComment = "数据的总数量";

			return statement;
		}

		/// <summary>
		/// Visual Basic
		/// </summary>
		public class VisualBasicLanguage : Language
		{
			/// <summary>
			/// 构造函数
			/// </summary>
			/// <param name="statement">语句对象</param>
			public VisualBasicLanguage(SelectCountStatement statement)
			{
				StatementObject = statement;
			}

			/// <summary>
			/// 获取SQL语句
			/// </summary>
			/// <returns>SQL语句</returns>
			public override string GetStatement()
			{
				string conditions = "";
				foreach (var condition in StatementObject.Conditions)
				{
					foreach (var texts in condition)
					{
						if (texts.Item1 != null)
						{
							conditions += texts.Item1;
						}
						else if (texts.Item2 != null)
						{
							conditions += "@" + texts.Item2.Target.Name;
						}
					}
				}

				const string format = "select count(*) from {0}{1};";
				return string.Format(format, StatementObject.TableObject.GetExplicitName(), conditions == "" ? "" : (" where " + conditions));
			}

			/// <summary>
			/// 转换成静态函数代码
			/// </summary>
			/// <returns>函数代码</returns>
			public override string ToStaticFunction()
			{
				return "";
			}
		}
	}
}
