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.config".
      /// </summary>
      public class Config : DbAccess, IConfigRepository
      {
          /// <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 "config".
          /// </summary>
          public override string _ObjectName => "config";
  
          /// <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.config".
          /// </summary>
          /// <returns>Returns the number of rows of the table "core.config".</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 \"Config\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT COUNT(*) FROM core.config;";
              return Factory.Scalar<long>(this._Catalog, sql);
          }
  
          /// <summary>
          /// Executes a select query on the table "core.config" to return all instances of the "Config" class. 
          /// </summary>
          /// <returns>Returns a non-live, non-mapped instances of "Config" 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.Config> 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 \"Config\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.config ORDER BY config_id;";
              return Factory.Get<MixERP.Net.Entities.Core.Config>(this._Catalog, sql);
          }
  
          /// <summary>
          /// Executes a select query on the table "core.config" to return all instances of the "Config" class to export. 
          /// </summary>
          /// <returns>Returns a non-live, non-mapped instances of "Config" 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 \"Config\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.config ORDER BY config_id;";
              return Factory.Get<dynamic>(this._Catalog, sql);
          }
  
          /// <summary>
          /// Executes a select query on the table "core.config" with a where filter on the column "config_id" to return a single instance of the "Config" class. 
          /// </summary>
          /// <param name="configId">The column "config_id" parameter used on where filter.</param>
          /// <returns>Returns a non-live, non-mapped instance of "Config" 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.Config Get(int configId)
          {
              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 \"Config\" filtered by \"ConfigId\" with value {ConfigId} was denied to the user with Login ID {_LoginId}", configId, this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.config WHERE config_id=@0;";
              return Factory.Get<MixERP.Net.Entities.Core.Config>(this._Catalog, sql, configId).FirstOrDefault();
          }
  
          /// <summary>
          /// Executes a select query on the table "core.config" with a where filter on the column "config_id" to return a multiple instances of the "Config" class. 
          /// </summary>
          /// <param name="configIds">Array of column "config_id" parameter used on where filter.</param>
          /// <returns>Returns a non-live, non-mapped collection of "Config" 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.Config> Get(int[] configIds)
          {
              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 \"Config\" was denied to the user with Login ID {LoginId}. configIds: {configIds}.", this._LoginId, configIds);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT * FROM core.config WHERE config_id IN (@0);";
  
              return Factory.Get<MixERP.Net.Entities.Core.Config>(this._Catalog, sql, configIds);
          }
  
          /// <summary>
          /// Custom fields are user defined form elements for core.config.
          /// </summary>
          /// <returns>Returns an enumerable custom field collection for the table core.config</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 \"Config\" 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.config' ORDER BY field_order;";
                  return Factory.Get<PetaPoco.CustomField>(this._Catalog, sql);
              }
  
              sql = "SELECT * from core.get_custom_field_definition('core.config'::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.config.
          /// </summary>
          /// <returns>Returns an enumerable name and value collection for the table core.config</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 \"Config\" was denied to the user with Login ID {LoginId}", this._LoginId);
                      throw new UnauthorizedException("Access is denied.");
                  }
              }
  
              const string sql = "SELECT config_id AS key, config_name as value FROM core.config;";
              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 Config class on the database table "core.config".
          /// </summary>
          /// <param name="config">The instance of "Config" 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 config, List<EntityParser.CustomField> customFields)
          {
              if (string.IsNullOrWhiteSpace(this._Catalog))
              {
                  return null;
              }
  
  
  
              object primaryKeyValue = config.config_id;
  
              if (Cast.To<int>(primaryKeyValue) > 0)
              {
                  primaryKeyValue = config.config_id;
                  this.Update(config, int.Parse(config.config_id));
              }
              else
              {
                  primaryKeyValue = this.Add(config);
              }
  
              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.config')" +
                           ");";
  
              Factory.NonQuery(this._Catalog, sql);
  
  
gt:             if (customFields == null)