﻿using LibDatabaseCodeMaker.Database.SqlStatement;

namespace LibDatabaseCodeMaker.Database
{
	/// <summary>
	/// Microsoft Office Access数据库
	/// </summary>
	public partial class Access : BasicDatabase
	{
		/// <summary>
		/// 创建C#对象
		/// </summary>
		public override void CreateCSharp()
		{
			const string format = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};User Id={1};Jet OLEDB:Database Password={2};";
			string connstr = string.Format(format, RelatePath == "" ? AbsolutePath : ("|DataDirectory|" + RelatePath), Username, Password);
			const string import = "System.Data.OleDb";
			const string connection = "OleDbConnection";
			const string command = "OleDbCommand";
			Target = new CSharp(this, connstr, import, connection, command);

			foreach (var table in Tables)
			{
				table.ChangeToCs();

				table.InsertIntoStatements.Add(InsertIntoStatement.CreateCsMethod<AccessInsertIntoStatement>(connection, command, table, this, table.Fields));
				table.NonStaticInsertIntoIndex = table.InsertIntoStatements.Count - 1;

				var insert2 = InsertIntoStatement.CreateCsStaticMethod<AccessInsertIntoStatement>(connection, command, table, this, table.Fields);
				if (insert2 != null)
				{
					table.InsertIntoStatements.Add(insert2);
				}

				var delete1 = DeleteStatement.CreateCsMethod(connection, command, table, this, table.Fields);
				if (delete1 != null)
				{
					table.DeleteStatements.Add(delete1);
					table.NonStaticDeleteIndex = table.DeleteStatements.Count - 1;
				}

				var delete2 = DeleteStatement.CreateCsStaticMethod(connection, command, table, this, table.Fields);
				if (delete2 != null)
				{
					table.DeleteStatements.Add(delete2);
				}

				var update = UpdateStatement.CreateCsMethod(connection, command, table, this, table.Fields);
				if (update != null)
				{
					table.UpdateStatements.Add(update);
					table.NonStaticUpdateIndex = table.UpdateStatements.Count - 1;
				}

				table.SelectCountStatements.Add(SelectCountStatement.CreateCsMethod(connection, command, table, this));
				table.SelectStatements.Add(AccessSelectStatement.CreateCsSelectAll(connection, command, table, this));

				var select = AccessSelectStatement.CreateCsSelectByKey(connection, command, table, this, table.Fields);
				if (select != null)
				{
					table.SelectStatements.Add(select);
				}

				table.SelectStatements.Add(AccessSelectStatement.CreateCsSelectRange(connection, command, table, this, table.Fields));
			}
		}
	}
}
