using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using fatd_faturamento.Bancos.Sicoob.Entidade;

namespace fatd_faturamento.Bancos.Sicoob
{
    public class TokenSicoob
    {
        public string GerarToken(string url, string clientId, string path, string certificadoSenha, string trustedServerCertPath)
        {
            string result = string.Empty;

            try
            {
                X509Certificate2 certificado = new X509Certificate2(path, certificadoSenha);

                using (HttpClient httpClient = new HttpClient(new HttpClientHandler
                {
                    ClientCertificateOptions = ClientCertificateOption.Manual,
                    SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
                    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true,
                    ClientCertificates = { certificado }
                }))
                {
                    var parameters = new Dictionary<string, string>
                {
                    { "client_id", clientId },
                    { "grant_type", "client_credentials" },
                    //{ "scope", "cob.read cob.write" } // Pix Somente
                    { "scope", "cobranca_boletos_consultar cobranca_boletos_incluir" }

                };

                    var content = new FormUrlEncodedContent(parameters);

                    var response = httpClient.PostAsync(url, content).Result;

                    string html = response.Content.ReadAsStringAsync().Result;

                    Token token = JsonConvert.DeserializeObject<Token>(html);

                    result = token.access_token;
                }
            }
            catch (Exception ex)
            {
                string retorno = "1 - Erro ao anexar certificado!!! " + ex.Message;
                result = retorno;
            }

            return result;
        }

    }
}
