using KarleyLibrary.Erweiterungen;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;

namespace WK5.Core.OpenCart
{
    public class CustomerGroup
    {
        #region Properties
        public int customer_group_id { get; set; }
        public bool approval { get; set; }
        public int sort_order { get; set; }
        #endregion

        public CustomerGroupDescription? Description { get; set; }

        public static async Task<CustomerGroup?> GetCustomerGroupAsync(int customer_group_id, string connectionString)
        {
            using MySqlController2 mySqlController = new MySqlController2(connectionString);

            mySqlController.AddParameter("@CUSTOMER_GROUP_ID", customer_group_id);
            DataRow row = await mySqlController.SelectRowAsync("SELECT * FROM customer_group WHERE customer_group_id = @CUSTOMER_GROUP_ID");

            return row == null ? null : ObjectErweiterung.DataRowZuObjekt(new CustomerGroup(), row);
        }

        public static async IAsyncEnumerable<CustomerGroup> GetCustomerGroupsAsync(string connectionString)
        {
            using MySqlController2 mySqlController = new MySqlController2(connectionString);

            DataTable data = await mySqlController.SelectDataAsync("SELECT customer_group_id FROM customer_group");
            foreach (DataRow row in data.Rows)
            {
                if (row is not null)
                {
                    int id = row.Field<int>("customer_group_id");
                    if (id > 0)
                    {
                        yield return await CreateAsync(id);
                    }
                }
            }
        }

        public static async Task<CustomerGroup?> CreateAsync(int customer_group_id)
        {
            CustomerGroup? group = await GetCustomerGroupAsync(customer_group_id, GlobalConfig.KarleyMySql);
            if (group is not null)
            {
                CustomerGroupDescription? desc = await CustomerGroupDescription.GetCustomerGroupDescriptionAsync(group.customer_group_id, GlobalConfig.KarleyMySql);
                group.Description = desc;

                return group;
            }
            else
            {
                return null;
            }
        }
    }
}
