using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

public class Program
{
#if DEBUG
    public const string LogFaturas = @"X:\Back\Carteira x.x\4Docs\import.txt";
#else
        public const string LogFaturas = "import.txt";
#endif

    private static HttpClient httpClient = new HttpClient();

    public static void Main()
    {
        for (int i = 1; i < 3; i++)
        {
            for (int j = 1; j < 7; j++)
            {
                DirectoryInfo pasta = new DirectoryInfo(@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\1 - INDIVIDUAIS");
                DirectoryInfo pasta_agrupadas = new DirectoryInfo(@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\2 - AGRUPADAS");

                if (LerPasta(pasta, agrupada: false))
                {
                    LerPasta(pasta_agrupadas, agrupada: true);
                }
            }
        }
    }

    public static bool LerPasta(DirectoryInfo pasta, bool agrupada)
    {
        if (pasta.Exists)
        {
            string token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ";

            // token = await req_token();
            FileInfo[] faturas = pasta.GetFiles("*.pdf");
            StreamWriter sw = new StreamWriter(LogFaturas, true);

            foreach (FileInfo fatura in faturas)
            {
                if (!IsFileLocked(fatura))
                {
                    HttpResponseMessage response = SendFatura(token, fatura.FullName, agrupada);
                    if (response.IsSuccessStatusCode)
                    {
                        var iD = JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("requestId");
                        fatura.MoveTo(fatura.Directory?.Parent?.FullName + $@"\3 - PROCESSANDO\ID {iD} - " + fatura.Name.Replace(",", string.Empty));
                        sw.Write(iD);
                        sw.Write(",");
                        sw.Write(",");
                        sw.WriteLine(fatura.FullName);
                    }
                }
            }

            sw.Close();
            return true;
        }
        else
        {
            return false;
        }
    }

    public static string? ReqToken()
    {
        var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/oauth2/token");

        var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("smart:vnqtvmesikjzyipc"));
        request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

        request.Content = new StringContent("grant_type=client_credentials");
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

        var response = httpClient.Send(request);

        return JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("access_token").GetString();
    }

    public static HttpResponseMessage SendFatura(string token, string fatura, bool agrupada)
    {
        var handler = new HttpClientHandler
        {
            //Proxy = new WebProxy("http://127.0.0.1:8888"),
            //UseProxy = true,
            //ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
        };

        using (var httpClient = new HttpClient(handler))
        {
            var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/parse");

            request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");

            var multipartContent = new MultipartFormDataContent();
            multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(fatura)), @"""file""", @$"""{Path.GetFileName(fatura)}""");
            multipartContent.ElementAt(0).Headers.Add("Content-Type", "application/pdf");

            multipartContent.Add(new StringContent($"{{\"callbackUrl\":\"https://api.4docs.cloud/v2/null\",\"pipelineName\":\"energy\",\"multiple\":{agrupada.ToString().ToLower()},\"clientData\":{{\"fatura_PATH\":\"{fatura.Replace(",", string.Empty)}\"}}}}"), "json");

            request.Content = multipartContent;

            return httpClient.Send(request);
        }
    }

    public static bool IsFileLocked(FileInfo file)
    {
        try
        {
            using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
            {
                stream.Close();
            }
        }
        catch (IOException)
        {
            // the file is unavailable because it is:
            // still being written to
            // or being processed by another thread
            // or does not exist (has already been processed)
            return true;
        }

        // file is not locked
        return false;
    }
}
