context: // ReSharper disable All
  using System.Collections.Generic;
  using System.Data;
  using System.Dynamic;
  using System.Linq;
  using MixERP.Net.DbFactory;
  using MixERP.Net.EntityParser;
  using MixERP.Net.Framework;
  using MixERP.Net.Framework.Extensions;
  using Npgsql;
  using PetaPoco;
  using Serilog;
  
  namespace MixERP.Net.Schemas.Core.Data
  {
      /// <summary>
      /// Provides simplified data access features to perform SCRUD operation on the database table "core.menus".
      /// </summary>
      public class Menu : DbAccess, IMenuRepository
      {
          /// <summary>
          /// The schema of this table. Returns literal "core".
          /// </summary>
          public override string _ObjectNamespace => "core";
  
          /// <summary>
          /// The schema unqualified name of this table. Returns literal "menus".
          /// </summary>
          public override string _ObjectName => "menus";
  
          /// <summary>
          /// Login id of application user accessing this table.
          /// </summary>
          public long _LoginId { get; set; }
  
          /// <summary>
          /// User id of application user accessing this table.
          /// </summary>
          public int _UserId { get; set; }
  
          /// <summary>
          /// The name of the database on which queries are being executed to.
          /// </summary>
          public string _Catalog { get; set; }
  
          /// <summary>
          /// Performs SQL count on the table "core.menus".
          /// </summary>
          /// <returns>Returns the number of rows of the table "core.menus".</returns>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public long Count()
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return 0;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to count entity \"Menu\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT COUNT(*) FROM core.menus;";
              return Factory.Scalar<long>(this._Catalog, sql);
          }
  
          /// <summary>
          /// Executes a select query on the table "core.menus" to return all instances of the "Menu" class. 
          /// </summary>
          /// <returns>Returns a non-live, non-mapped instances of "Menu" class.</returns>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public IEnumerable<MixERP.Net.Entities.Core.Menu> GetAll()
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to the export entity \"Menu\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.menus ORDER BY menu_id;";
              return Factory.Get<MixERP.Net.Entities.Core.Menu>(this._Catalog, sql);
          }
  
          /// <summary>
          /// Executes a select query on the table "core.menus" to return all instances of the "Menu" class to export. 
          /// </summary>
          /// <returns>Returns a non-live, non-mapped instances of "Menu" class.</returns>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public IEnumerable<dynamic> Export()
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to the export entity \"Menu\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.menus ORDER BY menu_id;";
              return Factory.Get<dynamic>(this._Catalog, sql);
          }
  
          /// <summary>
          /// Executes a select query on the table "core.menus" with a where filter on the column "menu_id" to return a single instance of the "Menu" class. 
          /// </summary>
          /// <param name="menuId">The column "menu_id" parameter used on where filter.</param>
          /// <returns>Returns a non-live, non-mapped instance of "Menu" class mapped to the database row.</returns>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public MixERP.Net.Entities.Core.Menu Get(int menuId)
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to the get entity \"Menu\" filtered by \"MenuId\" with value {MenuId} was denied to the user with Login ID {_LoginId}", menuId, this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.menus WHERE menu_id=@0;";
              return Factory.Get<MixERP.Net.Entities.Core.Menu>(this._Catalog, sql, menuId).FirstOrDefault();
          }
  
          /// <summary>
          /// Executes a select query on the table "core.menus" with a where filter on the column "menu_id" to return a multiple instances of the "Menu" class. 
          /// </summary>
          /// <param name="menuIds">Array of column "menu_id" parameter used on where filter.</param>
          /// <returns>Returns a non-live, non-mapped collection of "Menu" class mapped to the database row.</returns>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public IEnumerable<MixERP.Net.Entities.Core.Menu> Get(int[] menuIds)
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to entity \"Menu\" was denied to the user with Login ID {LoginId}. menuIds: {menuIds}.", this._LoginId, menuIds);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.menus WHERE menu_id IN (@0);";
  
              return Factory.Get<MixERP.Net.Entities.Core.Menu>(this._Catalog, sql, menuIds);
          }
  
          /// <summary>
          /// Custom fields are user defined form elements for core.menus.
          /// </summary>
          /// <returns>Returns an enumerable custom field collection for the table core.menus</returns>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public IEnumerable<PetaPoco.CustomField> GetCustomFields(string resourceId)
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to get custom fields for entity \"Menu\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              string sql;
              if (string.IsNullOrWhiteSpace(resourceId))
              {
                  sql = "SELECT * FROM core.custom_field_definition_view WHERE table_name='core.menus' ORDER BY field_order;";
                  return Factory.Get<PetaPoco.CustomField>(this._Catalog, sql);
              }
  
              sql = "SELECT * from core.get_custom_field_definition('core.menus'::text, @0::text) ORDER BY field_order;";
              return Factory.Get<PetaPoco.CustomField>(this._Catalog, sql, resourceId);
          }
  
          /// <summary>
          /// Displayfields provide a minimal name/value context for data binding the row collection of core.menus.
          /// </summary>
          /// <returns>Returns an enumerable name and value collection for the table core.menus</returns>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public IEnumerable<DisplayField> GetDisplayFields()
          {
              List<DisplayField> displayFields = new List<DisplayField>();
  
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return displayFields;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to get display field for entity \"Menu\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT menu_id AS key, menu_code as value FROM core.menus;";
              using (NpgsqlCommand command = new NpgsqlCommand(sql))
              {
                  using (DataTable table = DbOperation.GetDataTable(this._Catalog, command))
                  {
                      if (table?.Rows == null || table.Rows.Count == 0)
                      {
                          return displayFields;
                      }
  
                      foreach (DataRow row in table.Rows)
                      {
                          if (row != null)
                          {
                              DisplayField displayField = new DisplayField
                              {
                                  Key = row["key"].ToString(),
                                  Value = row["value"].ToString()
                              };
  
                              displayFields.Add(displayField);
                          }
                      }
                  }
              }
  
              return displayFields;
          }
  
          /// <summary>
          /// Inserts or updates the instance of Menu class on the database table "core.menus".
          /// </summary>
          /// <param name="menu">The instance of "Menu" class to insert or update.</param>
          /// <param name="customFields">The custom field collection.</param>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public object AddOrEdit(dynamic menu, List<EntityParser.CustomField> customFields)
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
              menu.audit_user_id = this._UserId;
              menu.audit_ts = System.DateTime.UtcNow;
  
              object primaryKeyValue = menu.menu_id;
  
              if (Cast.To<int>(primaryKeyValue) > 0)
              {
                  primaryKeyValue = menu.menu_id;
                  this.Update(menu, int.Parse(menu.menu_id));
              }
              else
              {
                  primaryKeyValue = this.Add(menu);
              }
  
              string sql = "DELETE FROM core.custom_fields WHERE custom_field_setup_id IN(" +
                           "SELECT custom_field_setup_id " +
                           "FROM core.custom_field_setup " +
                           "WHERE form_name=core.get_custom_field_form_name('core.menus')" +
                           ");";
  
              Factory.NonQuery(this._Catalog, sql);
  
              if (customFields == null)
              {
                  return primaryKeyValue;
              }
  
              foreach (var field in customFields)
              {
                  sql = "INSERT INTO core.custom_fields(custom_field_setup_id, resource_id, value) " +
                        "SELECT core.get_custom_field_setup_id_by_table_name('core.menus', @0::character varying(100)), " +
                        "@1, @2;";
  
                  Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value);
              }
  
              return primaryKeyValue;
          }
  
          /// <summary>
          /// Inserts the instance of Menu class on the database table "core.menus".
          /// </summary>
          /// <param name="menu">The instance of "Menu" class to insert.</param>
          /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
          public object Add(dynamic menu)
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false);
                  }
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to add entity \"Menu\" was denied to the user with Login ID {LoginId}. {Menu}", this._LoginId, menu);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              return Factory.Insert(this._Catalog, menu, "core.menus", "menu_id");
          }
  
          /// <summary>
          /// Inserts or updates multiple instances of Menu class on the database table "core.menus";
          /// </summary>
          /// <param name="menus">List of "Menu" class to import.</param>
          /// <returns></returns>
          public List<object> BulkImport(List<ExpandoObject> menus)
          {
              if (!this.SkipValidation)
              {
                  if (!this.Validated)
                  {
                      this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
                  }
  
                  if (!this.HasAccess)
                  {
                      Log.Information("Access to import entity \"Menu\" was denied to the user with Login ID {LoginId}. {menus}", this._LoginId, menus);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              var result = new List<object>();
              int line = 0;
              try
              {
                  using (Database db = new Database(Factory.GetConnectionString(this._Catalog), Factory.ProviderName))
                  {
                      using (Transaction transaction = db.GetTransaction())
                      {
                          foreach (dynamic menu in menus)
                          {
                              line++;
  
                              menu.audit_user_id = this._UserId;
                              menu.audit_ts = System.DateTime.UtcNow;
  
                              object primaryKeyValue = menu.menu_id;
  
  
gt:                             if (Cast.To<int>(primaryKeyValue) > 0)