using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using MarkdownEditor.Models;

namespace MarkdownEditor.Services;

/// <summary>
/// Service for persisting and restoring application session state.
/// Saves open tabs, file paths, and unsaved content to a JSON file in the app data directory.
/// </summary>
public class SessionService : ISessionService
{
    private readonly string _sessionFilePath;

    /// <summary>
    /// Initializes a new instance of the <see cref="SessionService"/> class.
    /// </summary>
    public SessionService()
    {
        // Store session file in app data directory
        var appDataPath = GetAppDataDirectory();
        Directory.CreateDirectory(appDataPath);
        _sessionFilePath = Path.Combine(appDataPath, "session.json");
    }

    /// <summary>
    /// Gets the application data directory for storing session files.
    /// </summary>
    /// <returns>The path to the app data directory.</returns>
    private static string GetAppDataDirectory()
    {
        var appName = "OrmentiaMarkus";
        
        // Use LocalApplicationData for cross-platform compatibility
        // On Windows: %LOCALAPPDATA%
        // On macOS: ~/Library/Application Support
        // On Linux: ~/.local/share
        var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        
        return Path.Combine(appDataPath, appName);
    }

    /// <inheritdoc/>
    public async Task SaveSessionAsync(IEnumerable<SessionTabInfo> tabs, int selectedTabIndex)
    {
        try
        {
            var sessionData = new SessionData
            {
                Tabs = tabs.ToList(),
                SelectedTabIndex = selectedTabIndex
            };

            var json = JsonSerializer.Serialize(sessionData, new JsonSerializerOptions
            {
                WriteIndented = true
            });

            await File.WriteAllTextAsync(_sessionFilePath, json);
        }
        catch
        {
            // Fail silently - session restoration is a convenience feature
        }
    }

    /// <inheritdoc/>
    public async Task<SessionData?> LoadSessionAsync()
    {
        try
        {
            if (!File.Exists(_sessionFilePath))
            {
                return null;
            }

            var json = await File.ReadAllTextAsync(_sessionFilePath);
            var sessionData = JsonSerializer.Deserialize<SessionData>(json);

            return sessionData;
        }
        catch
        {
            return null;
        }
    }

    /// <inheritdoc/>
    public async Task ClearSessionAsync()
    {
        try
        {
            if (File.Exists(_sessionFilePath))
            {
                File.Delete(_sessionFilePath);
            }
        }
        catch
        {
            // Error clearing session - fail silently
        }

        await Task.CompletedTask;
    }
}
