using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace CheckTimeHikvision
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
#if DEBUG
            args = new string[4];
            args[0] = "update";
            args[1] = "172.16.50.151";
            args[2] = "admin";
            args[3] = "4NUDZhJ7";
#endif
            string server, login, password;
            if (args.Length != 4) return;
            server = args[1];
            login = args[2];
            password = args[3];

            switch (args[0])
            {
                case "check":
                    string baseUrl = $"http://{server}";
                    var credCache = new CredentialCache();
                    credCache.Add(new Uri(baseUrl), "Digest", new NetworkCredential(login, password));
                    using (var handler = new HttpClientHandler
                    {
                        Credentials = credCache,
                        //ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
                    })
                    using (var httpClient = new HttpClient(handler))
                    {
                        string requestUrl = $"{baseUrl}/ISAPI/System/time/localTime";
                        var response = await httpClient.GetAsync(requestUrl);
                        try
                        {
                            response.EnsureSuccessStatusCode();
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("1");
                            return;
                        }
                        var r = await response.Content.ReadAsStringAsync();
                        var r2 = Convert.ToDateTime(r);
                        if (r2 <= DateTime.Now.AddMinutes(2) && r2 >= DateTime.Now.AddMinutes(-2))
                            Console.WriteLine("0");
                        else Console.WriteLine("1");
                    }
                    break;
                case "update":
                    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");
                    }
                    break;
                default:
                    break;
            }



        }
    }
}
