using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using BlackRockReportFunction.Bussines;
using ClockifyReport.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Spire.Xls;
//using Microsoft.Azure.WebJobs;

namespace ClockifyReport
{
    public class Function2
    {
        private readonly ILogger _logger;
        public Function2(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<Function2>();
        }

        [Function("Function2")]
        [BlobOutput("report-container", Connection = "AzureWebJobsStorage")]

        public async Task Run([QueueTrigger("clockify-queue", Connection = "AzureWebJobsStorage")]string myQueueItem)
        {
            var reportObject = JsonConvert.DeserializeObject<Root>(myQueueItem);
            var reportFile = ReportGenerator.GenerateReportContent(reportObject);

            string connection = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
            string containerName = "report-container";

            _logger.LogInformation(connection);

            var blobClient = new BlobContainerClient(connection, containerName);
            var blob = blobClient.GetBlobClient($"BlackRockReport_{DateTime.Now.ToString("f")}.xls");

            MemoryStream memoryStream = new MemoryStream();
            reportFile.SaveToStream(memoryStream);

            memoryStream.Position = 0;
            await blob.UploadAsync(memoryStream);

            _logger.LogInformation("File uploaded successfully!");
        }
    }
}
