using System.IO;
namespace DualScreenDemo
{
    public partial class PrimaryForm
    {
        private PromotionsAndMenuPanel promotionsAndMenuPanel;

        private void InitializePromotionsAndMenuPanel()
        {
            promotionsAndMenuPanel = new PromotionsAndMenuPanel();
            ResizeAndPositionControl(promotionsAndMenuPanel, 0, 0, 1440, 900);
            this.Controls.Add(promotionsAndMenuPanel);

            promotions = LoadImagesFromFolder("news");
            menu = LoadImagesFromFolder("foods");


        }

        /// <summary>
        /// 從指定資料夾載入所有 .jpg 圖片
        /// </summary>
        private List<Image> LoadImagesFromFolder(string folderName)
        {
            List<Image> images = new();
            string folderPath = Utils.Env.GetPath(folderName, "");

            if (folderPath.Equals("")) return images;

            string[] imageFiles = Directory.GetFiles(folderPath, "*.jpg");

            foreach (string filePath in imageFiles)
            {
                try
                {
                    using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    images.Add(Image.FromStream(new MemoryStream(ReadFully(fs))));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"載入圖片失敗：{filePath}，原因：{ex.Message}");
                }
            }

            return images;
        }

        /// <summary>
        /// 將 Stream 轉為 byte[]，用於避免 Image 檔案鎖定
        /// </summary>
        private byte[] ReadFully(Stream input)
        {
            using MemoryStream ms = new();
            input.CopyTo(ms);
            return ms.ToArray();
        }
    }
}