using Quasar.Server.Models;
using Quasar.Server.Networking;
using System;
using System.IO;
using System.Windows.Forms;

namespace Quasar.Server.Helper
{
    /// <summary>
    /// Manages client-specific data folders for organizing exports and logs.
    /// </summary>
    public static class ClientDataManager
    {
        /// <summary>
        /// Gets or creates a client-specific folder for storing data.
        /// </summary>
        /// <param name="client">The client to create folder for.</param>
        /// <param name="subfolder">Optional subfolder name (e.g., "SystemInfo", "Intelix", "Keylogger").</param>
        /// <returns>The full path to the client's data folder.</returns>
        public static string GetClientFolder(Client client, string subfolder = null)
        {
            // Create base Logs folder
            string logsPath = Path.Combine(Application.StartupPath, "Logs");
            if (!Directory.Exists(logsPath))
                Directory.CreateDirectory(logsPath);

            // Create client-specific folder using UserAtPc as identifier
            string clientIdentifier = SanitizeFileName(client.Value.UserAtPc);
            string clientFolder = Path.Combine(logsPath, clientIdentifier);
            
            if (!Directory.Exists(clientFolder))
                Directory.CreateDirectory(clientFolder);

            // If subfolder specified, create it
            if (!string.IsNullOrEmpty(subfolder))
            {
                clientFolder = Path.Combine(clientFolder, subfolder);
                if (!Directory.Exists(clientFolder))
                    Directory.CreateDirectory(clientFolder);
            }

            return clientFolder;
        }

        /// <summary>
        /// Generates a timestamped filename for client data.
        /// </summary>
        /// <param name="prefix">Prefix for the filename (e.g., "SystemInfo", "Intelix").</param>
        /// <param name="extension">File extension (e.g., ".json", ".zip").</param>
        /// <returns>A timestamped filename.</returns>
        public static string GenerateTimestampedFilename(string prefix, string extension)
        {
            string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            return $"{prefix}_{timestamp}{extension}";
        }

        /// <summary>
        /// Sanitizes a string to be used as a filename or folder name.
        /// </summary>
        private static string SanitizeFileName(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                return "Unknown";

            // Remove invalid filename characters
            char[] invalidChars = Path.GetInvalidFileNameChars();
            foreach (char c in invalidChars)
            {
                fileName = fileName.Replace(c, '_');
            }

            // Also replace colon which might be in IP addresses or timestamps
            fileName = fileName.Replace(':', '_');

            return fileName;
        }
    }
}
