using System.Diagnostics;
using System.Net;
using System.Reflection.Metadata;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;

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/","https://tvtokyo.mov3.co/hls/tvtokyo.m3u8"),
           Get_mov3_url("https://mov3.co/ja/tvasahi/","https://tvasahi.mov3.co/hls/tvasahi.m3u8"),
            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);
            }
        }
        public  async Task epg_xml_get(String url,string savePath,bool header_bool)
        {
           
            try
            {
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);

                }
               
             
            

                using var client = new HttpClient();
                if (header_bool == true)
                {
                    client.DefaultRequestHeaders.Add(
                        "User-Agent",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                        "AppleWebKit/537.36 (KHTML, like Gecko) " +
                        "Chrome/149.0.0.0 Safari/537.36");
                }


                string xml = await client.GetStringAsync(
                   url);

             
                
               
                 await File.WriteAllTextAsync(savePath, xml, Encoding.UTF8);



          


            }
            catch (Exception ex)
            {
                error.write_error_log(ex.Message + ex.StackTrace);
                Debug.WriteLine(ex.Message+ex.StackTrace);
               
            }
        }



    
     

      
    }
}
