using AutoMapper;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Logging;
using MTWorkHR.Application.Models;
using MTWorkHR.Application.Services.Interfaces;
using MTWorkHR.Core.Global;
using System.IO;
using System.Net.Http.Headers;

namespace MTWorkHR.Application.Services
{
    public class BlobFileService : IFileService
    {
       // private readonly AppSettingsConfiguration settings;
        private const string ContainerName = "blobcontainer";
        public const string SuccessMessageKey = "SuccessMessage";
        public const string ErrorMessageKey = "ErrorMessage";
        private readonly BlobServiceClient _blobServiceClient;
        private readonly BlobContainerClient _containerClient;
        private readonly ILogger<BlobFileService> _logger;

        public BlobFileService(BlobServiceClient blobServiceClient, ILogger<BlobFileService> logger)
        {
            _blobServiceClient = blobServiceClient;
            _containerClient = _blobServiceClient.GetBlobContainerClient(ContainerName);
            _containerClient.CreateIfNotExists();
            _logger = logger;
        }

        public async Task<AttachmentResponseDto> UploadFile(IFormFile file)
        {
            AttachmentResponseDto result = new AttachmentResponseDto();
            try
            {
                string uniqueFileName = GenerateUniqueFileName(file.FileName);
                var blobClient = _containerClient.GetBlobClient(uniqueFileName);

                if (blobClient != null)
                {
                    if (blobClient.ExistsAsync().Result)
                    {
                        uniqueFileName = GenerateUniqueFileName(file.FileName);
                    }
                    var status = await blobClient.UploadAsync(file.OpenReadStream(), true);
                    result.OriginalName = file.FileName;
                    result.FileName = uniqueFileName;
                    result.FilePath = blobClient.Uri.AbsoluteUri;
                    return result;
                }
                else
                    return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return result;
            }
        }
        public async Task<string> UploadFileCloud(AttachmentDto file)
        {
            try
            {
                // Generate a unique file name to avoid overwriting
                string uniqueFileName = GenerateUniqueFileName(file.FileName);
                var blobClient = _containerClient.GetBlobClient(uniqueFileName);

                if (blobClient != null)
                {
                    if (blobClient.ExistsAsync().Result)
                    {
                        uniqueFileName = GenerateUniqueFileName(file.FileName);
                    }
                    using (Stream fs = file.FileData.OpenReadStream())
                    {
                        // Upload the file to blob storage
                        await blobClient.UploadAsync(fs, true);
                        fs.Position = 0;

                        using (BinaryReader br = new BinaryReader(fs))
                        {
                            byte[] bytes = br.ReadBytes((Int32)fs.Length);
                            var headers = file.FileData.Headers;
                            file.Content = bytes;
                            file.ContentType = file.FileData.ContentType;
                            file.FilePath = blobClient.Uri.AbsoluteUri;
                            file.OriginalName = file.FileName;
                            file.FileName = uniqueFileName;
                        }
                    }
                    return blobClient.Uri.AbsoluteUri;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return "";
            }
        }

        // Helper method to generate a unique file name
        private string GenerateUniqueFileName(string originalFileName)
        {
            // Extract file name and extension
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFileName);
            string extension = Path.GetExtension(originalFileName);

            // Append a unique identifier (e.g., timestamp or GUID)
            string uniqueIdentifier = DateTime.UtcNow.Ticks.ToString(); // or Guid.NewGuid().ToString()
            return $"{fileNameWithoutExtension}_{uniqueIdentifier}{extension}";
        }


        public async Task<AttachmentResponseDto> UploadFile(byte[] pdfBytes, string fileName)
        {
            AttachmentResponseDto result = new AttachmentResponseDto();
            try
            {
                // Get a reference to the container
                //BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient("Contracts");

                // Create the container if it doesn’t exist
                //containerClient.CreateIfNotExists();
                var blobClient = _containerClient.GetBlobClient(fileName);
                if (blobClient != null)
                {
                    using (MemoryStream uploadStream = new MemoryStream(pdfBytes))
                    {
                        _logger.LogInformation("1--Contract uploadStream length={0}", pdfBytes.Length);

                        var status = await blobClient.UploadAsync(uploadStream, overwrite: true);
                        _logger.LogInformation("2--Contract uploadStream Status={0}, uri={1}", status, blobClient.Uri.AbsoluteUri);

                    }
                    result.FileName = fileName;
                    result.FilePath = blobClient.Uri.AbsoluteUri;
                    _logger.LogInformation("3--Contract upload finish path={0}", blobClient.Uri.AbsoluteUri);
                    return result;
                }
                else
                {
                    _logger.LogInformation("BlobClient is null when upload file ={0}", fileName);
                    return result;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return result;
            }
        }
        public async Task<BlobObject> Download(string url)
        {
            try
            {
                var fileName = new Uri(url).Segments.LastOrDefault();
                var blobClient = _containerClient.GetBlobClient(fileName);
                if(await blobClient.ExistsAsync())
                {
                    BlobDownloadResult content = await blobClient.DownloadContentAsync();
                    var downloadedData = content.Content.ToStream();
                    if (ImageExtensions.Contains(Path.GetExtension(fileName.ToUpperInvariant())))
                    {
                        var extension = Path.GetExtension(fileName);
                        return new BlobObject { Content = downloadedData, ContentType = "image/"+extension.Remove(0,1) };
                    }
                    else
                    {
                        return new BlobObject { Content = downloadedData, ContentType = content.Details.ContentType };
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public async Task<List<AttachmentResponseDto>> UploadFiles(List<IFormFile> files)
        {
            List<AttachmentResponseDto> msgs = new List<AttachmentResponseDto>();
            foreach (var formFile in files)
            {
                msgs.Add(await UploadFile(formFile));
            }
            return msgs;
        }
        
        public async Task<bool> Delete(string fileName)
        {
            try
            {
                var blobClient = _containerClient.GetBlobClient(fileName);
                await blobClient.DeleteIfExistsAsync();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public void CopyFileToCloud(ref List<AttachmentDto> attachments)
        {
            foreach(var attach in attachments)
            {
                if (attach.FileData != null)
                {
                    var resPath = UploadFileCloud(attach).Result;
                    //if (resPath != "")
                    //    attach.FilePath = resPath;
                }
                
            }
        }

        public bool CopyFileToActualFolder(string FileName)
        {
            throw new NotImplementedException();
        }

        public bool DeleteFileFromTempFolder(string FileName)
        {
            throw new NotImplementedException();
        }

        public string GetTempAttachmentPath()
        {
            throw new NotImplementedException();
        }

        public string GetActualAttachmentPath()
        {
            throw new NotImplementedException();
        }

        public Task<Tuple<MemoryStream, string, string>> GetFileDownloadInfo(string fileUrl)
        {
            throw new NotImplementedException();
        }

        public Task<bool> CopyFileToActualFolder(List<AttachmentDto> attachments)
        {
            throw new NotImplementedException();
        }


        string[] ImageExtensions = new string[]
           {
                ".JPEG"
                , ".JPG"
                , ".PNG"
              
           };
    }
}
