using POC_authentif_kestrel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace poc_authentif_httplistener
{
  class Program
  {
    public static string BaseAdress => "https://localhost:3333";

    static async Task Main(string[] args)
    {

      string CodeVerifier = GenerateCodeVerifier();

      var code_challenge = string.Empty;
      using (var sha256 = SHA256.Create())
      {
        var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(CodeVerifier));
        code_challenge = Convert.ToBase64String(challengeBytes)
                  .TrimEnd('=')
                  .Replace('+', '-')
                  .Replace('/', '_');
      }

      var listener = new LoopbackHttpListener(3333, null);

      // VARIABLE A RENSEIGNER
      string clientId = "VARIABLE A RENSEIGNER";
      string clientSecret = "VARIABLE A RENSEIGNER";
      string abonnement = "VARIABLE A RENSEIGNER";

      //appel login V3
      string url = $"https://api-login.ebp.com/connect/authorize/callback?client_id={clientId}&client_secret={clientSecret}&redirect_uri=" +
        BaseAdress + "/api/login/SigninRedirect&response_type=code&scope=openid%20profile%20offline_access&state=4e2a15864f564bd19375999c394baa01&code_challenge=" +
        code_challenge + "&code_challenge_method=S256&response_mode=query";

      Process.Start(new ProcessStartInfo()
      {
        UseShellExecute = true,
        FileName = url
      }
       );

      var result = await listener.WaitForCallbackAsync();
      var queryStringPlit = result.Substring(1).Split("&");
      Dictionary<string, string> dictionary =
                      queryStringPlit.ToDictionary(s => s.Split('=')[0], s => s.Split('=')[1]);


      using (HttpClient client = new HttpClient())
      {
        string body = $"client_id={clientId}&client_secret={clientSecret}&redirect_uri="
          + BaseAdress
          + "/api/login/SigninRedirect&grant_type=authorization_code&code=" + dictionary["code"] + "&code_verifier=" + CodeVerifier;
        var content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

        HttpResponseMessage response = await client.PostAsync("https://api-login.ebp.com/connect/token", content);
        TokenDto token = await response.Content.ReadFromJsonAsync<TokenDto>();

        // requete vers jupiter
        client.DefaultRequestHeaders.Add("ebp-subscription-key", abonnement);
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

        response = await client.GetAsync("https://api-developpeurs.ebp.com/gescom/api/v1/Folders");
        if (response.IsSuccessStatusCode)
        {
          var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
          Console.WriteLine("\n\n");
          Console.WriteLine(json.RootElement);
        }
        else
        {
          Console.WriteLine("Erreur\n\n");
        }

        Console.ReadKey();

      }
      listener.Dispose();
    }




    private static string GenerateCodeVerifier()
    {
      var rng = RandomNumberGenerator.Create();

      var bytes = new byte[32];
      rng.GetBytes(bytes);

      return Convert.ToBase64String(bytes)
      .TrimEnd('=')
      .Replace('+', '-')
      .Replace('/', '_');
    }
  }
}