using SWRIS.Core;
using System;
using System.IO;
using System.Text.Json;

namespace SWRIS.Extensions
{
    public class DatFileHandler
    {
        public static bool CreateDatFile(string filePath, MemoryStream memoryData)
        {
            try
            {
                byte[] bytes = memoryData.ToArray();
                JsonCryptoHelper.EncryptToFile(bytes, filePath, ConfigHelper.AesKey, ConfigHelper.AesIV);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"创建JSON文件失败: {ex.Message}", ex);
                return false;
            }
        }
        public static (string absolutePath, string relativePath) GetDatFilePath(string serialNo)
        {
            return GetDateFilePath(AppDomain.CurrentDomain.BaseDirectory, serialNo);
        }
        public static byte[] ReadDatFile(string filePath)
        {
            filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
            byte[] bytes = null;
            try
            {
                if (!File.Exists(filePath))
                {
                    return bytes;
                }
                bytes = JsonCryptoHelper.DecryptFromFile<byte[]>(filePath, ConfigHelper.AesKey, ConfigHelper.AesIV);
            }
            catch (JsonException jsonEx)
            {
                LogHelper.Error($"JSON反序列化失败: {jsonEx.Message}", jsonEx);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"读取文件失败: {ex.Message}", ex);
            }
            return bytes;
        }
        public static bool DeleteDatFile(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    return true;
                }
                File.Delete(filePath);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"删除文件失败: {ex.Message}", ex);
                return false;
            }
            return true;
        }
        private static (string absolutePath, string relativePath) GetDateFilePath(string baseDirectory, string serialNo)
        {
            string relativeFolder = Path.Combine("Data", DateTime.Now.ToString("yyyy-MM-dd"));
            string absoluteFolder = Path.Combine(baseDirectory, relativeFolder);
            if (!Directory.Exists(absoluteFolder))
            {
                Directory.CreateDirectory(absoluteFolder);
            }
            string relativePath = Path.Combine(relativeFolder, $"{serialNo}-{DateTime.Now:yyyy-MM-dd HH-mm-ss}.dat");// 相对路径
            string absolutePath = Path.Combine(baseDirectory, relativePath);// 绝对路径

            return (absolutePath, relativePath);
        }
    }
}
