using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using YoutubeExplode;
using YoutubeExplode.Videos.Streams;

namespace YouTubeDownloader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void btnDownload_Click(object sender, EventArgs e)
        {
            string[] videoUrls = txtUrls.Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

            if (videoUrls.Length == 0)
            {
                MessageBox.Show("Please enter at least one YouTube video URL.");
                return;
            }

            // Disable the download button while downloading
            btnDownload.Enabled = false;
            lblStatus.Text = "Status: Downloading...";

            var youtube = new YoutubeClient();
            var tasks = new List<Task>();

            progressBar.Maximum = videoUrls.Length;
            progressBar.Value = 0;

            foreach (var videoUrl in videoUrls)
            {
                tasks.Add(Task.Run(async () =>
                {
                    try
                    {
                        var video = await youtube.Videos.GetAsync(videoUrl);
                        var streamManifest = await youtube.Videos.Streams.GetManifestAsync(video.Id);
                        var streamInfo = streamManifest.GetMuxedStreams().GetWithHighestVideoQuality();

                        if (streamInfo != null)
                        {
                            var saveFileDialog = new SaveFileDialog
                            {
                                FileName = $"{video.Title}.mp4",
                                Filter = "MP4 Files|*.mp4"
                            };

                            if (InvokeRequired)
                            {
                                Invoke(new Action(() => saveFileDialog.ShowDialog()));
                            }
                            else
                            {
                                saveFileDialog.ShowDialog();
                            }

                            var filePath = saveFileDialog.FileName;

                            if (!string.IsNullOrWhiteSpace(filePath))
                            {
                                await youtube.Videos.Streams.DownloadAsync(streamInfo, filePath);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"An error occurred while downloading a video: {ex.Message}");
                    }
                    finally
                    {
                        Invoke(new Action(() => progressBar.Value++));
                    }
                }));
            }

            await Task.WhenAll(tasks);

            btnDownload.Enabled = true;
            lblStatus.Text = "Status: Waiting";
            progressBar.Value = 0;

            MessageBox.Show("All videos have been downloaded.");
        }
    }
}