using KarleyLibrary.Attributes;
using KarleyLibrary.Erweiterungen;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WK5.Core.OpenCart
{
    public class ProductImage
    {
        [CompareField("product_image_id")]
        public int ProductImageId { get; set; }
        [CompareField("product_id")]
        public int ProductId { get; set; }
        public string? Image { get; set; }
        [CompareField("sort_order")]
        public int SortOrder { get; set; }

        internal static async IAsyncEnumerable<T> GetImagesAsync<T>(int product_id, string connectionString)
        {
            using MySqlController2 mySqlController = new MySqlController2(connectionString);

            string sql = $@" SELECT * FROM `product_image` WHERE product_id = @product_id";
            mySqlController.AddParameter("@product_id", product_id);

            DataTable data = await mySqlController.SelectDataAsync(sql);

            foreach (DataRow row in data.Rows)
            {
                if (row is not null)
                {
                    yield return ObjectErweiterung.DataRowZuObjekt(ObjectErweiterung.InstanceFromType<T>(), row);
                }
            }
        }

        public static async IAsyncEnumerable<T> GetImagesAsync<T>(string model, string connectionString)
        {
            using MySqlController2 mySqlController = new MySqlController2(connectionString);

            string sql = $@"
(SELECT `image` from product where model = @model) 
UNION ALL 
(SELECT pi.image FROM `product_image` pi LEFT JOIN product p ON p.product_id = pi.product_id WHERE UPPER(p.model) = @model)";
            mySqlController.AddParameter("@model", model.ToUpper());

            DataTable data = await mySqlController.SelectDataAsync(sql);

            foreach (DataRow row in data.Rows)
            {
                if (row is not null)
                {
                    yield return ObjectErweiterung.DataRowZuObjekt(ObjectErweiterung.InstanceFromType<T>(), row);
                }
            }
        }

        public async Task UpdateImageAsync()
        {
            using MySqlController2 mySqlController = new MySqlController2(GlobalConfig.MachMichMysql);
            string baseProps = GetUpdateProperties(mySqlController);

            string sql = $@"UPDATE `product_image` SET
{baseProps}

WHERE product_image_id = @product_image_id";

            await mySqlController.QueryAsync(sql);
        }

        public async Task DeleteImageAsync()
        {
            using MySqlController2 mySqlController = new MySqlController2(GlobalConfig.MachMichMysql);
            string sql = $@"DELETE FROM `product_image` WHERE product_image_id = @product_image_id";
            mySqlController.AddParameter("@product_image_id", ProductImageId);

            await mySqlController.QueryAsync(sql);
        }

        internal string GetUpdateProperties(MySqlController2? mySqlController = null)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("product_id = @product_id,");
            sb.AppendLine("image = @image,");
            sb.AppendLine("sort_order = @sort_order");

            if (mySqlController is not null)
            {
                mySqlController.AddParameter("@product_image_id", ProductImageId);
                mySqlController.AddParameter("@product_id", ProductId);
                mySqlController.AddParameter("@image", Image);
                mySqlController.AddParameter("@sort_order", SortOrder);

            }

            return sb.ToString();
        }

        internal Task<string?> Download(string baseUrl, string targetPath)
        {
            string remoteImageLink = $"{baseUrl}{Image}";
            string? dirname = Path.GetDirectoryName(targetPath);
            if (String.IsNullOrWhiteSpace(dirname))
            {
                return Task.FromResult<string?>(null);
            }

            (bool success, string nachricht) dirResult = FileErweiterung.EnsureCreateDirectory(dirname);

            if (dirResult.success)
            {
                try
                {
                    using WebClient client = new WebClient();
                    client.DownloadFileAsync(new Uri(remoteImageLink), targetPath);
                    return Task.FromResult<string?>(targetPath);
                }
                catch (Exception)
                {
                    return Task.FromResult<string?>(null);
                }
            }

            return Task.FromResult<string?>(null);
        }

    }
}
