using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO;

namespace WorkFlowCheck.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SystemController : ControllerBase
    {

        private readonly ISystemService _systemService;

        public SystemController(ISystemService systemService)
        {
            _systemService = systemService;
        }

        [HttpGet("GetDatabaseAndVersionInfo")]
        public async Task<ApiResponseDTO<string>> GetDatabaseAndVersionInfo()
        {
            var retVal = new ApiResponseDTO<string>()
            {
                IsSuccess = true,
            };
            var result = await _systemService.GetDatabaseAndVersionInfoAsync();

            if (result != null)
            {
                retVal.IsSuccess = true;
                retVal.Data = result;
            }
            else
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add("No data!");
            }

            return retVal;
        }

        [HttpGet("GetAllImageFiles")]
        public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllImageFilesAsync()
        {
            var retVal = new ApiResponseDTO<List<ImageFileDTO>>()
            {
                IsSuccess = true,
            };
            try
            {
                var allowedExtensions = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp", ".tiff" };
                var imageFolder = Path.Combine(Directory.GetCurrentDirectory(), "Images");
                var files = Directory.GetFiles(imageFolder)
                        .Where(f => allowedExtensions.Contains(Path.GetExtension(f).ToLower()))
                        .Select(f =>
                        {
                            var fileInfo = new FileInfo(f);
                            return new
                            {
                                FileName = fileInfo.Name,
                                FileSize = FormatFileSize(fileInfo.Length),
                                CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
                            };
                        });

                var checkListFileInfos = new List<ImageFileDTO>();
                foreach (var file in files.OrderBy(o => o.FileName).ToList())
                {
                    var checkListFileInfoDTO = new ImageFileDTO()
                    {
                        FileName = file.FileName,
                        FileSize = file.FileSize,
                        CreateDate = file.CreatedDate,

                    };
                    checkListFileInfos.Add(checkListFileInfoDTO);
                }

                if (checkListFileInfos != null)
                {
                    retVal.IsSuccess = true;
                    retVal.Data = checkListFileInfos;
                }
                else
                {
                    retVal.IsSuccess = false;
                    retVal.Errors.Add("No data!");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
            return retVal;
        }
        [HttpGet("GetAllPDFFiles")]
        public async Task<ApiResponseDTO<List<ImageFileDTO>>> GetAllPDFilesAsync()
        {
            var retVal = new ApiResponseDTO<List<ImageFileDTO>>()
            {
                IsSuccess = true,
            };
            try
            {
                var pdfFolder = Path.Combine(Directory.GetCurrentDirectory(), "PDF");
                var files = Directory.GetFiles(pdfFolder, "*.pdf")
                        .Select(f =>
                        {
                            var fileInfo = new FileInfo(f);
                            return new
                            {
                                FileName = fileInfo.Name,
                                FileSize = FormatFileSize(fileInfo.Length),
                                CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
                            };
                        });

                var checkListFileInfos = new List<ImageFileDTO>();
                foreach (var file in files.OrderBy(o => o.FileName).ToList())
                {
                    var checkListFileInfoDTO = new ImageFileDTO()
                    {
                        FileName = file.FileName,
                        FileSize = file.FileSize,
                        CreateDate = file.CreatedDate,

                    };
                    checkListFileInfos.Add(checkListFileInfoDTO);
                }

                if (checkListFileInfos != null)
                {
                    retVal.IsSuccess = true;
                    retVal.Data = checkListFileInfos;
                }
                else
                {
                    retVal.IsSuccess = false;
                    retVal.Errors.Add("No data!");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
            return retVal;
        }
        [HttpGet("GetAllLogAuditFiles")]
        public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogAuditFilesAsync()
        {
            var retVal = new ApiResponseDTO<List<LogFileDTO>>()
            {
                IsSuccess = true,
            };
            try
            {
                var logAuditFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow");
                var files = Directory.GetFiles(logAuditFiles, "*.log")
                        .Select(f =>
                        {
                            var fileInfo = new FileInfo(f);
                            return new
                            {
                                FileName = fileInfo.Name,
                                FileSize = FormatFileSize(fileInfo.Length),
                                CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
                            };
                        });

                var checkListFileInfos = new List<LogFileDTO>();
                foreach (var file in files.OrderBy(o => o.FileName).ToList())
                {
                    var checkListFileInfoDTO = new LogFileDTO()
                    {
                        FileName = file.FileName,
                        FileSize = file.FileSize,
                        CreateDate = file.CreatedDate,

                    };
                    checkListFileInfos.Add(checkListFileInfoDTO);
                }

                if (checkListFileInfos != null)
                {
                    retVal.IsSuccess = true;
                    retVal.Data = checkListFileInfos;
                }
                else
                {
                    retVal.IsSuccess = false;
                    retVal.Errors.Add("No data!");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
            return retVal;
        }
        [HttpGet("GetAllLogBusinessFiles")]
        public async Task<ApiResponseDTO<List<LogFileDTO>>> GetAllLogBusinessFilesAsync()
        {
            var retVal = new ApiResponseDTO<List<LogFileDTO>>()
            {
                IsSuccess = true,
            };
            try
            {
                var logBusinessFiles = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow");
                var files = Directory.GetFiles(logBusinessFiles, "*.log")
                        .Select(f =>
                        {
                            var fileInfo = new FileInfo(f);
                            return new
                            {
                                FileName = fileInfo.Name,
                                FileSize = FormatFileSize(fileInfo.Length),
                                CreatedDate = fileInfo.CreationTime.ToString("yyyy.MM.dd HH:mm"),
                            };
                        });

                var checkListFileInfos = new List<LogFileDTO>();
                foreach (var file in files.OrderBy(o => o.FileName).ToList())
                {
                    var checkListFileInfoDTO = new LogFileDTO()
                    {
                        FileName = file.FileName,
                        FileSize = file.FileSize,
                        CreateDate = file.CreatedDate,

                    };
                    checkListFileInfos.Add(checkListFileInfoDTO);
                }

                if (checkListFileInfos != null)
                {
                    retVal.IsSuccess = true;
                    retVal.Data = checkListFileInfos;
                }
                else
                {
                    retVal.IsSuccess = false;
                    retVal.Errors.Add("No data!");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
            return retVal;
        }

        [HttpGet("DownloadFile/{filename}")]
        public async Task<ApiResponseDTO<byte[]>> DownloadFile(string filename)
        {
            var retVal = new ApiResponseDTO<byte[]>()
            {
                IsSuccess = false,
            };
            var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Images", filename);

            if (!System.IO.File.Exists(imageFile))
            {
                retVal.Errors.Add($"{filename} does not exist");
                return retVal;
            }

            byte[] response = System.IO.File.ReadAllBytes(imageFile);


            if (response != null)
            {

                retVal.IsSuccess = true;
                retVal.Data = response;
            }
            else
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add("No data!");
            }

            return retVal;
        }
        [HttpGet("DownloadPDFFile/{filename}")]
        public async Task<ApiResponseDTO<byte[]>> DownloadPDFFile(string filename)
        {
            var retVal = new ApiResponseDTO<byte[]>()
            {
                IsSuccess = false,
            };
            var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "PDF", filename);

            if (!System.IO.File.Exists(imageFile))
            {
                retVal.Errors.Add($"{filename} does not exist");
                return retVal;
            }

            byte[] response = System.IO.File.ReadAllBytes(imageFile);


            if (response != null)
            {

                retVal.IsSuccess = true;
                retVal.Data = response;
            }
            else
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add("No data!");
            }

            return retVal;
        }


        [HttpGet("DownloadAuditLogFile/{filename}")]
        public async Task<ApiResponseDTO<byte[]>> DownloadAuditLogFile(string filename)
        {
            var retVal = new ApiResponseDTO<byte[]>()
            {
                IsSuccess = false,
            };
            var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\AuditFlow", filename);

            if (!System.IO.File.Exists(imageFile))
            {
                retVal.Errors.Add($"{filename} does not exist");
                return retVal;
            }

            byte[] response = System.IO.File.ReadAllBytes(imageFile);


            if (response != null)
            {

                retVal.IsSuccess = true;
                retVal.Data = response;
            }
            else
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add("No data!");
            }

            return retVal;
        }
        [HttpGet("DownloadBusinessLogFile/{filename}")]
        public async Task<ApiResponseDTO<byte[]>> DownloadBusinessLogFile(string filename)
        {
            var retVal = new ApiResponseDTO<byte[]>()
            {
                IsSuccess = false,
            };
            var imageFile = Path.Combine(Directory.GetCurrentDirectory(), "Logs\\BusinessFlow", filename);

            if (!System.IO.File.Exists(imageFile))
            {
                retVal.Errors.Add($"{filename} does not exist");
                return retVal;
            }

            byte[] response = System.IO.File.ReadAllBytes(imageFile);


            if (response != null)
            {

                retVal.IsSuccess = true;
                retVal.Data = response;
            }
            else
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add("No data!");
            }

            return retVal;
        }

        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB", "TB" };
            double len = bytes;
            int order = 0;
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len /= 1024;
            }
            return $"{len:0.##} {sizes[order]}";
        }
    }
}
