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

namespace DragonVideoPlayer
{
    public class Web_update
    {
        private static readonly HttpClient client = new HttpClient();
       
            public  void YtDlpUpdate(string ytDlpPath)
        {
          
            if (!File.Exists(ytDlpPath))
                    return;
         
                Process.Start(new ProcessStartInfo
                {
                    FileName = ytDlpPath,
                    Arguments = "-U",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WorkingDirectory = Path.GetDirectoryName(ytDlpPath)
                });
            }

   
        public async Task update_mov3()
        {
            File.WriteAllText("mov3.txt", ""); // ←ここで1回だけ

            var tasks = new List<Task>
    {
         Get_mov3_url("https://mov3.co/ja/ntv/","https://ntv5.mov3.co/hls/ntv.m3u8"),
            Get_mov3_url("https://mov3.co/ja/tvtokyo/",""),
           Get_mov3_url("https://mov3.co/ja/tvasahi/",""),
            Get_mov3_url("https://mov3.co/ja/fujitv/","https://fujitv4.mov3.co/hls/fujitv.m3u8"),
            Get_mov3_url("https://mov3.co/ja/tbs/","https://tbs5.mov3.co/hls/tbs.m3u8"),
             Get_mov3_url("https://mov3.co/ja/tokyomx/",""),
             Get_mov3_url("https://mov3.co/ja/nhk/","https://nhk4.mov3.co/hls/nhk.m3u8"),
    };

            await Task.WhenAll(tasks);
        }
        private static readonly object _lock = new object();


        private async Task mov3_write(string url)
        {
            try
            {

                // 並列書き込み対策
                lock (_lock)
                {
                    File.AppendAllText("mov3.txt", url + Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
        public async Task Get_mov3_url(string url, String m3u8_url)
        {
            try
            {
                var result = await client.GetAsync(url);
                var html = await result.Content.ReadAsStringAsync();

                var reg = new Regex(@"ok.ru/videoembed/([0-9]+)", RegexOptions.IgnoreCase);
                var match = reg.Match(html);
                string okru = "";
                while (match.Success)
                {
                    okru = "https://ok.ru/videoembed/" + match.Groups[1].Value;



                    await mov3_write(okru);

                    match = match.NextMatch(); // ★これ重要
                }
                if (string.IsNullOrEmpty(okru))
                {

                    await mov3_write(m3u8_url);
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

        private async Task<List<string>> GetAbemaChannelListAsync()
        {
            var list = new List<string>();

            try
            {
                var result = await client.GetAsync(
                    "https://raw.githubusercontent.com/karenda-jp/AbemaTV/main/abema240P.m3u");

                var html = await result.Content.ReadAsStringAsync();

                var reg = new System.Text.RegularExpressions.Regex(
                    @"https://linear-abematv.akamaized.net/preview/channel/([\-_a-zA-Z0-9]+)/playlist.m3u8",
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                var match = reg.Match(html);

                while (match.Success)
                {
                    list.Add(match.Groups[1].Value);
                    match = match.NextMatch();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            return list;
        }
        public async Task AbemaUpdateFilesAsync()
        {
            var list = await GetAbemaChannelListAsync();

            if (list.Count <= 2) return;

            try
            {
                File.WriteAllText("abema.txt", "");
                File.WriteAllText("abema2.txt", "");

                foreach (var id in list)
                {
                    await File.AppendAllTextAsync("abema.txt",
                        $"https://linear-abematv.akamaized.net/preview/channel/{id}/playlist.m3u8{Environment.NewLine}");

                    await File.AppendAllTextAsync("abema2.txt",
                        $"https://abema.tv/now-on-air/{id}{Environment.NewLine}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
        private async Task<List<string>> GetArvaChannelListAsync()
        {
            var list = new List<string>();

            try
            {
                var result = await client.GetAsync(
                    "https://arva.netgenx.site/stream/master.m3u?pass=1");

                var html = await result.Content.ReadAsStringAsync();
                Debug.WriteLine(html);
                var reg = new System.Text.RegularExpressions.Regex(
                    @"(https?:\/\/arva.netgenx.site\/stream\/.+?.m3u.+?hls)",
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                var match = reg.Match(html);

                while (match.Success)
                {
                    list.Add(match.Groups[1].Value);
                    match = match.NextMatch();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            return list;
        }
        public async Task ArvaUpdateFilesAsync()
        {
            Debug.WriteLine("ArvaUpdateFilesAsy");
            var list = await GetArvaChannelListAsync();
            Debug.WriteLine(list.Count);
            if (list.Count <= 2) return;

            try
            {
                File.WriteAllText("arva.txt", "");
             

                foreach (var url in list)
                {
                    Debug.WriteLine(url);
                    await File.AppendAllTextAsync("arva.txt",
                        $"{url}{Environment.NewLine}");

                        }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

        internal async Task arvaUpdateFilesAsync()
        {
            throw new NotImplementedException();
        }
    }
}
