// OverlayForm/OverlayForm.Labels.cs
using System.IO;
using DBObj;
using DualScreenDemo;
namespace OverlayFormObj
{
    public partial class OverlayForm
    {
        public Label displayLabel;
        //public Label songDisplayLabel;
        private List<Label> displayLabels;
        public Label pauseLabel;
        public Label muteLabel; // New mute label
        public Label topLeftLabel;
        public Label topRightLabel;
        private System.Windows.Forms.Timer topRightTimer = new System.Windows.Forms.Timer();
        private System.Windows.Forms.Timer secondLineDisplayTimer = new System.Windows.Forms.Timer();
        private System.Windows.Forms.Timer qrCodeTimer = new System.Windows.Forms.Timer();
        private System.Windows.Forms.Timer delayTimer = new System.Windows.Forms.Timer();
        

        private void InitializeLabels()
        {
            InitializeBlackBackgroundPanel();
            InitializeDisplayLabel();
            InitializeDisplayLabels();
            InitializePauseLabel();
            InitializeMuteLabel(); // Initialize the new mute label
            InitializeTopRightLabel();
            InitializeTopLeftLabel();
            ConfigureKeyTimers();
        }


        private void ConfigureKeyTimers()
        {
            topRightTimer.Interval = 1000;
            topRightTimer.Tick += (sender, e) => { topRightLabel.Visible = false; topRightTimer.Stop(); RedisplayTopRigthLabel(); };

            secondLineDisplayTimer.Interval = 32000;
            secondLineDisplayTimer.Tick += SecondLineDisplayTimer_Tick;

            // Initialize Timer for hiding QR code
            qrCodeTimer.Interval = 10000; // 10 seconds
            qrCodeTimer.Tick += QrCodeTimer_Tick;
        }

        private void QrCodeTimer_Tick(object sender, EventArgs e)
        {
            showQRCode = false;
            qrCodeTimer.Stop();
            Invalidate(); // Trigger a repaint to hide the QR code
        }

        public void DisplayQRCodeOnOverlay(string randomFolderPath)
        {
            try
            {
                string qrImagePath = Path.Combine(Application.StartupPath, "themes/superstar/_www", randomFolderPath, "qrcode.png");
                if (!File.Exists(qrImagePath))
                {
                    Console.WriteLine("QR code image not found: " + qrImagePath);
                    return;
                }
                for (int i = 0; i < 3; i++)
                {
                    try
                    {
                        using (var fs = new FileStream(qrImagePath, FileMode.Open, FileAccess.Read))
                        {
                            qrCodeImage = Image.FromStream(fs);
                        }
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error loading QR code image: " + ex.Message);
                        System.Threading.Thread.Sleep(100); // Wait a bit before retrying
                    }
                }

                if (qrCodeImage == null)
                {
                    Console.WriteLine("Failed to load QR code image after multiple attempts.");
                    return;
                }

                showQRCode = true;
                qrCodeTimer.Start();
                Invalidate(); // Trigger a repaint to show the QR code
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in DisplayQRCodeOnOverlay: " + ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Inner exception: " + ex.InnerException.Message);
                }
            }
        }

        private void SecondLineDisplayTimer_Tick(object sender, EventArgs e)
        {
            secondLineDisplayTimer.Stop();
            marqueeTextSecondLine = "";
            marqueeXPosSecondLine = this.Width;
            Invalidate();

        }

        private void InitializeDisplayLabel()
        {
            displayLabel = new Label();
            displayLabel.Location = new Point(100, 50);
            displayLabel.AutoSize = true;
            displayLabel.ForeColor = Color.White;
            displayLabel.Font = new Font("Microsoft JhengHei", 34, FontStyle.Bold);
            displayLabel.BackColor = Color.Black;
            this.Controls.Add(displayLabel);
            displayLabel.Location = new Point(10, 56);
        }

        // private void InitializeSongDisplayLabel()
        // {
        //     songDisplayLabel = new Label();
        //     songDisplayLabel.Location = new Point(0, 50); // 設置顯示位置
        //     songDisplayLabel.AutoSize = true;
        //     songDisplayLabel.ForeColor = Color.White;
        //     songDisplayLabel.Font = new Font("Microsoft JhengHei", 125, FontStyle.Bold); // 設定字體樣式
        //     songDisplayLabel.BackColor = Color.Black;
        //     this.Controls.Add(songDisplayLabel);
        // }

        private void InitializeDisplayLabels()
        {
            displayLabels = new List<Label>();

            for (int i = 0; i < 6; i++) // Assuming a maximum of 6 lines
            {
                Label displayLabel = new Label
                {
                    AutoSize = true,
                    ForeColor = Color.White,
                    Font = new Font("Microsoft JhengHei", 25, FontStyle.Bold), // 設定字體樣式
                    BackColor = Color.Transparent
                };
                displayLabels.Add(displayLabel);
                this.Controls.Add(displayLabel);
            }
        }
        // 播放暫停，字體大小
        private void InitializePauseLabel()
        {
            pauseLabel = new Label();
            pauseLabel.AutoSize = false;
            pauseLabel.Font = new Font("Microsoft JhengHei", 75, FontStyle.Bold);
            pauseLabel.BackColor = Color.Transparent;
            pauseLabel.TextAlign = ContentAlignment.MiddleCenter;
            pauseLabel.Size = new Size(1080, 200);
            pauseLabel.Location = new Point(
            (this.Width - pauseLabel.Width) / 2,  // 水平居中
            (this.Height - pauseLabel.Height) / 2 + 500 // 垂直居中偏下 50 像素
            );

            pauseLabel.Paint += (s, e) =>
            {
                string text = "播放暫停";
                Font font = pauseLabel.Font;
                Graphics g = e.Graphics;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                // 描邊（多次偏移繪製）
                using (Brush outlineBrush = new SolidBrush(Color.Black))
                {
                    for (int x = -2; x <= 2; x++)
                    {
                        for (int y = -2; y <= 2; y++)
                        {
                            if (x != 0 || y != 0)
                            {
                                g.DrawString(text, font, outlineBrush,
                                    new PointF((pauseLabel.Width - g.MeasureString(text, font).Width) / 2 + x,
                                            (pauseLabel.Height - g.MeasureString(text, font).Height) / 2 + y));
                            }
                        }
                    }
                }

                // 中心白色文字
                using (Brush textBrush = new SolidBrush(Color.White))
                {
                    g.DrawString(text, font, textBrush,
                        new PointF((pauseLabel.Width - g.MeasureString(text, font).Width) / 2,
                                (pauseLabel.Height - g.MeasureString(text, font).Height) / 2));
                }
            };
            this.Controls.Add(pauseLabel);
        }

        // 播放靜音，字體大小
        private void InitializeMuteLabel()
        {
            muteLabel = new Label();
            muteLabel.AutoSize = false;
            muteLabel.Visible = false;
            muteLabel.Font = new Font("Microsoft JhengHei", 75, FontStyle.Bold);
            muteLabel.BackColor = Color.Transparent;
            muteLabel.TextAlign = ContentAlignment.MiddleCenter;
            muteLabel.Size = new Size(1080, 200);
            muteLabel.Location = new Point(
            (this.Width - muteLabel.Width) / 2,  // 水平居中
            (this.Height - muteLabel.Height) / 2 + 250 // 垂直居中偏下 50 像素
            );

            muteLabel.Paint += (s, e) =>
            {
                string text = "【全部靜音】";
                Font font = muteLabel.Font;
                Graphics g = e.Graphics;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                // 描邊（多次偏移繪製）
                using (Brush outlineBrush = new SolidBrush(Color.Black))
                {
                    for (int x = -2; x <= 2; x++)
                    {
                        for (int y = -2; y <= 2; y++)
                        {
                            if (x != 0 || y != 0)
                            {
                                g.DrawString(text, font, outlineBrush,
                                    new PointF((muteLabel.Width - g.MeasureString(text, font).Width) / 2 + x,
                                            (muteLabel.Height - g.MeasureString(text, font).Height) / 2 + y));
                            }
                        }
                    }
                }

                // 中心白色文字
                using (Brush textBrush = new SolidBrush(Color.White))
                {
                    g.DrawString(text, font, textBrush,
                        new PointF((muteLabel.Width - g.MeasureString(text, font).Width) / 2,
                                (muteLabel.Height - g.MeasureString(text, font).Height) / 2));
                }
            };
            this.Controls.Add(muteLabel);
        }
        public Panel blackBackgroundPanel;

        private void InitializeBlackBackgroundPanel()
        {
            blackBackgroundPanel = new Panel
            {
                BackColor = Color.FromArgb(255, 0, 0, 0), // 黑色背景
                Size = new Size(this.Width, 120), // 高度 100 像素
                Location = new Point(0, 0), // 从画面顶部开始
                Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top // 固定顶部
            };

            // 設置 Paint 事件處理程序
            blackBackgroundPanel.Paint += (sender, e) =>
            {
                using (Font largeFont = new Font("微軟正黑體", 34, FontStyle.Bold))
                using (Font secondLineFont = new Font("微軟正黑體", 34, FontStyle.Bold))
                using (Brush whiteBrush = new SolidBrush(Color.White))
                using (Brush RedBrush = new SolidBrush(Color.Red))
                using (Brush marqueeBrush = new SolidBrush(marqueeTextColor))
                using (Brush backgroundBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 0)))
                {
                    // 第一行文字的代码保持不变
                    SizeF textSize = e.Graphics.MeasureString(marqueeText, largeFont);
                    float yPosition1 = 0;
                    e.Graphics.FillRectangle(backgroundBrush, marqueeXPos, yPosition1, textSize.Width, textSize.Height);
                    e.Graphics.DrawString(marqueeText, largeFont, marqueeBrush, new PointF(marqueeXPos, yPosition1));

                    // 修改第二行文字的部分
                    float yPosition2 = 56;
                    Rectangle clipRect = new Rectangle(
                        (int)(this.Width / 32),  // 从1/8改成1/16（因为要居中）
                        (int)yPosition2,
                        (int)(15 * this.Width / 16),  // 从3/4改成7/8
                        (int)textSize.Height
                    );
                    Region originalClip = e.Graphics.Clip;
                    e.Graphics.SetClip(clipRect);

                    // 获取当前应该显示的文字段落
                    string displayText = textSegments.Count > 0 ? textSegments[currentSegmentIndex] : marqueeTextSecondLine;
                    SizeF textSizeSecondLine = e.Graphics.MeasureString(displayText, secondLineFont);
                    float centeredXPos = (this.Width - textSizeSecondLine.Width) / 2;
                    e.Graphics.FillRectangle(backgroundBrush, centeredXPos, yPosition2, textSizeSecondLine.Width, textSizeSecondLine.Height);
                    // 系統公告塗色調整區域
                    e.Graphics.DrawString(displayText, secondLineFont, RedBrush, new PointF(centeredXPos, yPosition2));

                    // 还原裁剪区域
                    e.Graphics.Clip = originalClip;

                }
            };

            this.Controls.Add(blackBackgroundPanel);

            blackBackgroundPanel.SendToBack();
        }

        private void InitializeTopLeftLabel()
        {
            topLeftLabel = new Label
            {
                AutoSize = true,
                ForeColor = Color.White,
                Font = new Font("Microsoft JhengHei", 32, FontStyle.Regular),
                BackColor = Color.Transparent,
                Text = "",
                Visible = true
            };
            blackBackgroundPanel.Controls.Add(topLeftLabel);

            topLeftLabel.Location = new Point(10, 56);
        }



        // 更新 nextSongLabel 標籤的文本
        public void UpdateTopLeftLabel(string text)
        {
            if (topLeftLabel == null)
            {
                return;
            }

            topLeftLabel.Text = text;
            topLeftLabel.Visible = true; // 確保標籤顯示
            Console.WriteLine($"更新顯示: {text}");
        }

        private void InitializeTopRightLabel()
        {
            topRightLabel = new Label
            {
                AutoSize = true,
                ForeColor = Color.White,
                Font = new Font("Microsoft JhengHei", 34, FontStyle.Bold),
                BackColor = Color.Transparent,
                Text = "標準迴音",
                Visible = true
            };
            blackBackgroundPanel.Controls.Add(topRightLabel);
            blackBackgroundPanel.Resize += (s, e) =>
            {
                topRightLabel.Location = new Point(blackBackgroundPanel.Width - topRightLabel.Width - 10, 56);
            };
        }
        // 显示标准标签


        public void ShowPauseLabel() => pauseLabel.Visible = true;

        // 隐藏暂停标签
        public void HidePauseLabel() => pauseLabel.Visible = false;

        // 显示静音标签
        public void ShowMuteLabel() => muteLabel.Visible = true;

        // 隐藏静音标签
        public void HideMuteLabel() => muteLabel.Visible = false;
        public void ShowTopRightLabel(string customText = "", string tag = null)
        {
            if (tag != null)
            {
                PrimaryForm.SendCommandThroughSerialPort(tag);
            }
            HideTopRightLabels();
            topRightLabel.Text = customText;
            topRightLabel.Visible = true;
        }
        public void ShowTopRightLabelTime(string customText = "", string tag = null)
        {
            ShowTopRightLabel(customText, tag);
            topRightTimer.Stop();
            topRightTimer.Start();
        }
        public void ShowTopRightEchoLabel(string customText = "")
        {
            switchmic = customText;
            ShowTopRightLabel(customText);
        }
        private string switchmic = "標準迴音";
        // 隐藏所有标签
        public void HideTopRightLabels()
        {
            topRightLabel.Visible = false;
        }
        public void RedisplayTopRigthLabel()
        {
            HideTopRightLabels();
            ShowTopRightEchoLabel(switchmic);
        }
        public async void DisplayBarrage(string text)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => DisplayBarrage(text)));
                return;
            }

            Label lblBarrage = new Label
            {
                Text = "藏鏡人:", // 一開始不顯示任何字
                AutoSize = true,
                ForeColor = Color.White,
                Font = new Font("Microsoft JhengHei", 34, FontStyle.Bold),
                Location = new Point(10, this.Height / 2)
            };

            this.Controls.Add(lblBarrage);
            lblBarrage.BringToFront();

            // 逐字顯示文字
            for (int i = 0; i < text.Length; i++)
            {
                lblBarrage.Text += text[i];
                await Task.Delay(500); // 每個字間隔 200ms，可依喜好調整
            }
            // 完成後停留 2 秒
            await Task.Delay(5000);

            // 閃爍三下
            for (int i = 0; i < 3; i++)
            {
                lblBarrage.Visible = false;
                await Task.Delay(300);
                lblBarrage.Visible = true;
                await Task.Delay(300);
            }
            this.Controls.Remove(lblBarrage);
            lblBarrage.Dispose();
        }

        /*
        public void DisplayBarrage1(string text)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new System.Action(() => DisplayBarrage1(text)));  
                return;
            }

            
            Random rnd = new Random();

            
            for (int i = 0; i < 30; i++) 
            {
                Label lblBarrage = new Label
                {
                    Text = text, 
                    AutoSize = true, 
                    ForeColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256)), 
                    Font = new Font("Arial", rnd.Next(10, 50)), 
                    Location = new Point(rnd.Next(0, this.Width), rnd.Next(0, this.Height)) 
                };

                
                this.Controls.Add(lblBarrage);
                lblBarrage.BringToFront(); 

                
                System.Windows.Forms.Timer moveTimer = new System.Windows.Forms.Timer { Interval = 50 }; 
                moveTimer.Tick += (sender, e) =>
                {
                    lblBarrage.Left -= 5; 

                    if (lblBarrage.Right < 0) 
                    {
                        lblBarrage.Dispose();
                        moveTimer.Dispose();
                    }
                };
                moveTimer.Start();

                
                int duration = rnd.Next(3000, 7000); 
                System.Windows.Forms.Timer durationTimer = new System.Windows.Forms.Timer { Interval = duration };
                durationTimer.Tick += (sender, e) =>
                {
                    if (moveTimer.Enabled)
                    {
                        moveTimer.Stop(); 
                        moveTimer.Dispose();
                    }

                    this.Controls.Remove(lblBarrage);
                    lblBarrage.Dispose();
                    durationTimer.Stop(); 
                    durationTimer.Dispose();
                };
                durationTimer.Start();
            }
        }
        */
    }
}