using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;


namespace DragonVideoPlayer
{


    public partial class InfoForm : Form
    {
        private VideoState _videoState;
        private PictureBox pic;
        StringBuilder sb;
        public InfoForm(VideoState state)
        {

            _videoState = state;
            InitializeUI();
            this.Load += Form1_Load;
        }
    
        private TextBox lbl;
        private void AddLine(string title, string value)
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
              //  sb.AppendLine(title + "：" + value);
                SafeAppendText(lbl, title + "：" + value );

            }
        }

        public static async Task<string> GetTitleAsync(string url)
        {
            var psi = new ProcessStartInfo
            {
                FileName = "yt-dlp.exe",
                Arguments = $"--get-title \"{url}\"",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (var process = new Process())
            {
                process.StartInfo = psi;

                process.Start();

                string output = await process.StandardOutput.ReadToEndAsync();
                string error = await process.StandardError.ReadToEndAsync();

                await process.WaitForExitAsync();

                if (process.ExitCode != 0)
                {
                    throw new Exception($"yt-dlp error: {error}");
                }

                return output.Trim();
            }
        }

        private void cap_creat(string movie_path, string img_path)
        {

            if (System.IO.File.Exists(img_path))
            {

                return;
            }

            int THUMB_SIZE = 256;


            try
            {
                Bitmap thumbnail = WindowsThumbnailProvider.GetThumbnail(
                  movie_path, THUMB_SIZE, THUMB_SIZE, ThumbnailOptions.None);

                thumbnail.Save(img_path, System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (Exception ex)
            {

                Debug.WriteLine(ex.Message + ex.StackTrace);

            }

        }
        private void InitializeUI()
        {
            sb= new StringBuilder();
            // フォーム設定（InfoForm）
            this.Text = _videoState.video_title;
            this.Width = 600;
            this.Height = 600;

            lbl = new TextBox();
            String label_txt = "動画情報" + Environment.NewLine;
            pic = new PictureBox();

            // 位置とサイズ
            pic.Location = new Point(160, 00);
            //480, 300
            pic.Size = new Size(320, 200);

            // 画像表示方法
            pic.SizeMode = PictureBoxSizeMode.Zoom;
           
            // フォームに追加
            this.Controls.Add(pic);
            if (!string.IsNullOrWhiteSpace(_videoState.url))
            {
                LinkLabel link = new LinkLabel();

                link.Text = _videoState.url;

                link.Location = new Point(20, 170);
                link.Width = 200;
                link.Links.Add(0, link.Text.Length, _videoState.url);

                link.LinkClicked += (s, e) =>
                {
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = e.Link.LinkData.ToString(),
                        UseShellExecute = true
                    });
                };
                this.Controls.Add(link);
            }
            lbl.Text = label_txt;
            lbl.Height = 500;
            lbl.Width = 600;
            lbl.ScrollBars = ScrollBars.Vertical;
            lbl.ReadOnly = true;
            lbl.Multiline = true;
          
            lbl.WordWrap = true;    // 自動改行

            lbl.Location = new Point(20, 200);
            lbl.AutoSize = false;          // 文字サイズに合わせる
            lbl.Font = new Font("Yu Gothic UI", 12);
            lbl.ForeColor = Color.Black;

            this.Controls.Add(lbl);
        }



        static string ConvertUrlToFileName(string url)
        {
            // https:// または http:// を削除
            string result = Regex.Replace(url, @"^https?://", "");

            // / を _
            result = result.Replace("/", "_");

            // Windows禁止文字を削除
            result = Regex.Replace(result, @"[\\:*?""<>|]", "");

            return result;
        }

        static void DownloadThumbnail(string url, string outputFileName)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName = "yt-dlp",
                    Arguments = $"--write-thumbnail --convert-thumbnails jpg --skip-download -o \"{outputFileName}\" \"{url}\"",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };


                
                using (Process process = Process.Start(psi))
                {
                    process.WaitForExit();
                }

            }
            catch (Exception ex)
            {

                Debug.WriteLine(ex.Message + ex.StackTrace);

            }



        }



        private static string FormatBitrate(string bitStr)
        {
            if (string.IsNullOrEmpty(bitStr))
                return "";

            if (!double.TryParse(bitStr, out double bit))
                return "";

            if (bit >= 1_000_000)
                return (bit / 1_000_000).ToString("0.0") + " Mbps";
            else
                return (bit / 1000).ToString("0") + " kbps";
        }
        private static string FormatSize(double size)
        {

            if (size >= 1_000_000_000)
                return (size / 1_000_000_000).ToString("0.0") + "G";
            else if (size >= 1_000_000)
                return (size / 1_000_000).ToString("0") + "M";
            else
                return (size / 1000).ToString("0") + "K";
        }
        private async void Form1_Load(object sender, EventArgs e)
        {
             
            String path = _videoState.Full_path;
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (Regex.IsMatch(path, @"\.m3u8", RegexOptions.IgnoreCase)||
                Regex.IsMatch(path, @"naori\-test.netgenx.site", RegexOptions.IgnoreCase) ||
          

            System.Text.RegularExpressions.Regex.IsMatch(path, config_class.config_text_read("streamlinkで取得するURLの正規表現"), System.Text.RegularExpressions.RegexOptions.IgnoreCase) 
             )
                {
               
              
                    if (!string.IsNullOrWhiteSpace(_videoState.logo_img_path))
                    {
                        try
                        {

                            pic.ImageLocation = _videoState.logo_img_path;
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message + ex.StackTrace);
                        }
                }
                else
                {

                    pic.Visible = false;
                    lbl.Location = new Point(20, 20);
                    lbl.Height = 540;
                }
               

            }
            if (System.IO.File.Exists(path))
            {
                if (config_class.config_bool_read("サムネイル作成") == true)
                {

                    string img_path = path;
                    img_path = img_path.Replace(@":\", "_");
                    img_path = img_path.Replace(@"\", "_");
                    img_path = img_path + ".jpg";

                    if (System.IO.File.Exists("./img/" + img_path) == false)
                    {

                        await Task.Run(async () =>
                        {
                            cap_creat(path, "./img/" + img_path);
                        });
                    }
                    if (System.IO.File.Exists("./img/" + img_path) == true)
                    {
                        try
                        {
                            using (var fs = new FileStream("./img/" + img_path, FileMode.Open, FileAccess.Read))
                            {
                                pic.Image = Image.FromStream(fs);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message + ex.StackTrace);
                        }
                    }
                }
                else
                {
                    pic.Visible = false;
                    lbl.Location = new Point(20, 20);
                    lbl.Height = 540;

                }


            }
            else
            {
                if (!string.IsNullOrEmpty(path) &&
    Regex.IsMatch(path, @"https?:\/\/", RegexOptions.IgnoreCase)&&
    !Regex.IsMatch(path, @"\.m3u8", RegexOptions.IgnoreCase)&&
        !Regex.IsMatch(path, @"naori\-test.netgenx.site", RegexOptions.IgnoreCase) )
                {
                 
                    String img_base = ConvertUrlToFileName(path);
                    string dir = "./img/";
                    string file = Path.Combine(dir, img_base + ".jpg");

                    if (System.IO.File.Exists(file) == false)
                    {

                        await Task.Run(() =>
                        {
                            DownloadThumbnail(path, Path.Combine(dir, img_base));
                        });
                    }

                       if (System.IO.File.Exists(file) == true)
                    {
                        if (file != null)
                        {
                            try
                            {
                                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                                using (var img = Image.FromStream(fs))
                                {
                                    pic.Image = new Bitmap(img);
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message + ex.StackTrace);
                            }
                        }



                    }
                }
            }
           

            String duration_st = System.TimeSpan.FromSeconds(_videoState.duration).ToString(@"h\:mm\:ss");
            String size_st = FormatSize(_videoState.filesize);

            String text = "";

         
       
           

            if (System.IO.File.Exists(path))
            {
                String filename = System.IO.Path.GetFileName(path);


                AddLine("ファイル名" , filename + Environment.NewLine);
                AddLine("フルパス：" , path + Environment.NewLine);
                AddLine("解像度", _videoState.videoWidth + "x" + _videoState.videoHeight + Environment.NewLine);
                
                AddLine("再生時間：", duration_st + Environment.NewLine);
                AddLine("ビデオコーデック：" , _videoState.video_codec + Environment.NewLine);
                   AddLine("ビデオビットレート", FormatBitrate(_videoState.video_bitrate) + Environment.NewLine);
                AddLine("FPS(メタタグ）", _videoState.container_fps + Environment.NewLine);
                AddLine("FPS(実測値）", _videoState.estimated_fps + Environment.NewLine);
                AddLine("オーディオコーデック", _videoState.audio_codec + Environment.NewLine);
                AddLine("オーディオビットレート", FormatBitrate(_videoState.audio_bitrate) + Environment.NewLine);
                AddLine("サイズ：" , size_st + Environment.NewLine);
                AddLine("ファイル作成日：" , System.IO.File.GetCreationTime(path) + Environment.NewLine);
                AddLine("ファイル更新日：" , System.IO.File.GetLastWriteTime(path) + Environment.NewLine);

                text = sb.ToString();

            }
            else
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(path, "https?:", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {


                  


                    AddLine("url", path + Environment.NewLine);
                    if (_videoState.videoWidth > 0 && _videoState.videoHeight > 0)
                    {
                        AddLine("解像度", _videoState.videoWidth + "x" + _videoState.videoHeight + Environment.NewLine);
                    }
                        AddLine("チャンネル名", _videoState.channel_name + Environment.NewLine);
                    AddLine("番組名", _videoState.bangumi_title + Environment.NewLine);
                    AddLine("番組内容", _videoState.description + Environment.NewLine);
                    AddLine("ジャンル", _videoState.category + Environment.NewLine);
                    AddLine("パーソナリティ", _videoState.pfm + Environment.NewLine);

                    AddLine("ビデオコーデック", _videoState.video_codec + Environment.NewLine);
                    AddLine("ビデオビットレート", FormatBitrate(_videoState.video_bitrate) + Environment.NewLine);
                    AddLine("FPS(メタタグ）", _videoState.container_fps + Environment.NewLine);
                    AddLine("FPS(実測値）", _videoState.estimated_fps + Environment.NewLine);
                    AddLine("オーディオコーデック", _videoState.audio_codec + Environment.NewLine);
                    AddLine("オーディオビットレート", FormatBitrate(_videoState.audio_bitrate) + Environment.NewLine);
                    text = sb.ToString();
                }
            }

            SafeAppendText(lbl, text);




            if (System.Text.RegularExpressions.Regex.IsMatch(path, "https?:", System.Text.RegularExpressions.RegexOptions.IgnoreCase) &&
                System.IO.File.Exists(path) == false)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(path, config_class.config_text_read("streamlinkで取得するURLの正規表現"), System.Text.RegularExpressions.RegexOptions.IgnoreCase) ||
                System.Text.RegularExpressions.Regex.IsMatch(path, ".m3u8", System.Text.RegularExpressions.RegexOptions.IgnoreCase)||
                      Regex.IsMatch(path, @"naori\-test.netgenx.site", RegexOptions.IgnoreCase) 
)
                {
                

                }
                else
                {
                    string title = "";
                    try
                    {
                        title = await GetTitleAsync(path);
                    }
                    catch (Exception ex)
                    {

                        Console.WriteLine(ex.Message + ex.StackTrace);


                    }
                   SafeAppendText(lbl, "タイトル(yr-dlp)：" + title + Environment.NewLine);







                }
            }

          
        }

        private void SafeAppendText(TextBox lbl, string text)
        {
            if (lbl.IsDisposed || !lbl.IsHandleCreated)
                return;

            if (lbl.InvokeRequired)
            {
                lbl.BeginInvoke(new Action(() =>
                {
                    if (!lbl.IsDisposed)
                        lbl.AppendText(text);
                }));
            }
            else
            {
                lbl.AppendText(text);
            }
        }
    }
}