using System.Net;
using System.Net.NetworkInformation;
using System.Text;

namespace SetVideoDataHikvision
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var list = new List<string>();
            var lines = File.ReadAllLines("listCam.csv");
            foreach (var line in lines)
            {
                list.Add(line);
            }
            foreach (var host in list)
            {
                using (Ping ping = new Ping())
                {
                    PingReply pingReply = ping.Send(host);
                    if (pingReply.Status != IPStatus.Success)
                    {
                        Console.WriteLine($"{host}\t NO PING");
                        continue;
                    }
                }
                string baseUrlU = $"http://{server}";
                var credCacheU = new CredentialCache();
                credCacheU.Add(new Uri(baseUrlU), "Digest", new NetworkCredential(login, password));
                using (var handler = new HttpClientHandler
                {
                    Credentials = credCacheU,
                    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
                })
                using (var httpClient = new HttpClient(handler))
                {
                    string requestUrl = $"{baseUrlU}/ISAPI/System/time";

                    string xmlBody = $@"<?xml version=""1.0"" encoding=""UTF-8""?><Time><timeMode>manual</timeMode><localTime>{DateTime.Now:yyyy-MM-ddTHH:mm:ss}</localTime><timeZone>CST-3:00:00</timeZone></Time>";

                    // Создаем контент для PUT запроса
                    var content = new StringContent(xmlBody, Encoding.UTF8, "application/xml");

                    // Выполняем PUT запрос
                    var response = await httpClient.PutAsync(requestUrl, content);
                    try
                    {
                        response.EnsureSuccessStatusCode();
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("1");
                        return;
                    }
                    var r = await response.Content.ReadAsStringAsync();
                    //r = r.Replace("\r\n", "");
                    if (r.StartsWith("OK"))
                    {
                        Console.WriteLine("0");
                    }
                    else Console.WriteLine("1");
                }
            }
        }
    }
}
