using System.Diagnostics;
using System.Text.RegularExpressions;

namespace DragonVideoPlayer
{


    public partial class InfoForm : Form
    {
        private VideoState _videoState;
        private PictureBox pic;

        public InfoForm(VideoState state)
        {

            _videoState = state;
            InitializeUI();
            this.Load += Form1_Load;
        }
        private TextBox lbl;
        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()
        {
            // フォーム設定（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(200, 00);
            pic.Size = new Size(256, 192);

            // 画像表示方法
            pic.SizeMode = PictureBoxSizeMode.Zoom;



            // フォームに追加
            this.Controls.Add(pic);
            lbl.Text = label_txt;
            lbl.Height = 500;
            lbl.Width = 600;
            lbl.ScrollBars = ScrollBars.Vertical;
            lbl.ReadOnly = true;
            lbl.Multiline = true;
            lbl.Location = new Point(20, 200);
            lbl.AutoSize = true;          // 文字サイズに合わせる
            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
                };


                Debug.WriteLine(psi.Arguments);
                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 (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
            {
                if (!string.IsNullOrEmpty(path) &&
    Regex.IsMatch(path, "https?:", 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);

                text +=
  "ファイル名" + filename + Environment.NewLine +
   "フルパス：" + path + Environment.NewLine +

     "タイトル：" + _videoState.video_title + Environment.NewLine +
     "解像度：" + _videoState.videoWidth + "x" + _videoState.videoHeight + Environment.NewLine +
     "再生時間：" + duration_st + Environment.NewLine +
   "ビデオコーデック：" + _videoState.video_codec + Environment.NewLine +
       "ビデオビットレート：" + FormatBitrate(_videoState.video_bitrate) + Environment.NewLine +
         "FPS(メタタグ）：" + _videoState.container_fps + Environment.NewLine +
       "FPS(実測値）：" + _videoState.estimated_fps + Environment.NewLine +


     "オーディオコーデック：" + _videoState.audio_codec + Environment.NewLine +
      "オーディオビットレート：" + FormatBitrate(_videoState.audio_bitrate) + Environment.NewLine +

     "サイズ：" + size_st + Environment.NewLine +
     "ファイル作成日：" + System.IO.File.GetCreationTime(path) + Environment.NewLine +
     "ファイル更新日：" + System.IO.File.GetLastWriteTime(path) + Environment.NewLine;
            }
            else
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(path, "https?:", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {


                    text = "url：" + path + Environment.NewLine +


     "解像度：" + _videoState.videoWidth + "x" + _videoState.videoHeight + Environment.NewLine +
     "再生時間：" + duration_st + Environment.NewLine +
  "ビデオコーデック：" + _videoState.video_codec + Environment.NewLine +
       "ビデオビットレート：" + FormatBitrate(_videoState.video_bitrate) + Environment.NewLine +
         "FPS(メタタグ）：" + _videoState.container_fps + Environment.NewLine +
       "FPS(実測値）：" + _videoState.estimated_fps + Environment.NewLine +


     "オーディオコーデック：" + _videoState.audio_codec + Environment.NewLine +
      "オーディオビットレート：" + FormatBitrate(_videoState.audio_bitrate) + Environment.NewLine +


     "サイズ：" + size_st + Environment.NewLine;

                    Debug.WriteLine(text);

                }
            }

            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, ".msu", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    SafeAppendText(lbl, "タイトル：" + _videoState.video_title + Environment.NewLine);



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

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


                    }
                    SafeAppendText(lbl, "タイトル：" + 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);
            }
        }
    }
}