using System;
using System.IO;
using Microsoft.Azure.Functions.Worker;
//using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using RestSharp;
using RestSharp.Authenticators;

namespace ClockifyReport
{
    public class Function3
    {

        private readonly ILogger _logger;

        private static string SenderAddress = Environment.GetEnvironmentVariable("SenderAddress");
        private static string SenderDisplayName = Environment.GetEnvironmentVariable("SenderDisplayName");
        private static string MailGunApiKey = Environment.GetEnvironmentVariable("MailGunApiKey");
        private static string Domain = Environment.GetEnvironmentVariable("Domain");
        private static string MailTo = Environment.GetEnvironmentVariable("MailTo");

        public Function3(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<Function3>();
        }

        [Function("Function3")]
        public void Run([BlobTrigger("report-container/{name}", Connection = "AzureWebJobsStorage")] byte[] fileData, string name, ILogger log)
        {
            string fileName = string.Format($"BlackRockReport_{DateTime.Now.ToString("f")}.xlsx");

            var client = new RestClient("https://api.mailgun.net/v3");
            client.Authenticator = new HttpBasicAuthenticator("api", MailGunApiKey);


            MemoryStream memoryStream = new MemoryStream(fileData);
            memoryStream.Position = 0;

            RestRequest request = new RestRequest();
            request.AddParameter("domain", Domain, ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", $"{SenderDisplayName} <{SenderAddress}>");
            request.AddParameter("to", MailTo);
            request.AddParameter("subject", "BlackRock Report");
            request.AddParameter("html", string.Format("Here is yours report for current week. {0}", fileName));
            request.AddFile("attachment", memoryStream.ToArray(), fileName);
            request.Method = Method.Post;
            client.Execute(request);





            _logger.LogInformation("Email sent successfully!");
        }
    }
}
