using System.Runtime.InteropServices;

namespace Terminal.Gui.Drivers;

/// <summary>
///     Provides the main implementation of the driver abstraction layer for Terminal.Gui.
///     This implementation of <see cref="IDriver"/> coordinates the interaction between input processing, output
///     rendering,
///     screen size monitoring, and ANSI escape sequence handling.
/// </summary>
/// <remarks>
///     <para>
///         <see cref="DriverImpl"/> implements <see cref="IDriver"/>,
///         serving as the central coordination point for console I/O operations. It delegates functionality
///         to specialized components:
///     </para>
///     <list type="bullet">
///         <item><see cref="IInputProcessor"/> - Processes keyboard and mouse input</item>
///         <item><see cref="IOutputBuffer"/> - Manages the screen buffer state</item>
///         <item><see cref="IOutput"/> - Handles actual console output rendering</item>
///         <item><see cref="AnsiRequestScheduler"/> - Manages ANSI escape sequence requests</item>
///         <item><see cref="ISizeMonitor"/> - Monitors terminal size changes</item>
///     </list>
///     <para>
///         This class is internal and should not be used directly by application code.
///         Applications interact with drivers through the <see cref="Application"/> class.
///     </para>
/// </remarks>
internal class DriverImpl : IDriver
{
    private readonly IOutput _output;
    private readonly AnsiRequestScheduler _ansiRequestScheduler;
    private CursorVisibility _lastCursor = CursorVisibility.Default;

    /// <summary>
    ///     Initializes a new instance of the <see cref="DriverImpl"/> class.
    /// </summary>
    /// <param name="inputProcessor">The input processor for handling keyboard and mouse events.</param>
    /// <param name="outputBuffer">The output buffer for managing screen state.</param>
    /// <param name="output">The output interface for rendering to the console.</param>
    /// <param name="ansiRequestScheduler">The scheduler for managing ANSI escape sequence requests.</param>
    /// <param name="sizeMonitor">The monitor for tracking terminal size changes.</param>
    public DriverImpl (
        IInputProcessor inputProcessor,
        IOutputBuffer outputBuffer,
        IOutput output,
        AnsiRequestScheduler ansiRequestScheduler,
        ISizeMonitor sizeMonitor
    )
    {
        InputProcessor = inputProcessor;
        _output = output;
        OutputBuffer = outputBuffer;
        _ansiRequestScheduler = ansiRequestScheduler;

        InputProcessor.KeyDown += (s, e) => KeyDown?.Invoke (s, e);
        InputProcessor.KeyUp += (s, e) => KeyUp?.Invoke (s, e);

        InputProcessor.MouseEvent += (s, e) =>
                                     {
                                         //Logging.Logger.LogTrace ($"Mouse {e.Flags} at x={e.ScreenPosition.X} y={e.ScreenPosition.Y}");
                                         MouseEvent?.Invoke (s, e);
                                     };

        SizeMonitor = sizeMonitor;

        sizeMonitor.SizeChanged += (_, e) =>
                                   {
                                       SetScreenSize (e.Size!.Value.Width, e.Size.Value.Height);

                                       //SizeChanged?.Invoke (this, e);
                                   };

        CreateClipboard ();
    }

    /// <summary>
    ///     The event fired when the screen changes (size, position, etc.).
    /// </summary>
    public event EventHandler<SizeChangedEventArgs>? SizeChanged;

    /// <inheritdoc/>
    public IInputProcessor InputProcessor { get; }

    /// <inheritdoc/>
    public IOutputBuffer OutputBuffer { get; }

    /// <inheritdoc/>
    public ISizeMonitor SizeMonitor { get; }


    private void CreateClipboard ()
    {
        if (InputProcessor.DriverName is { } && InputProcessor.DriverName.Contains ("fake"))
        {
            if (Clipboard is null)
            {
                Clipboard = new FakeClipboard ();
            }

            return;
        }

        PlatformID p = Environment.OSVersion.Platform;

        if (p is PlatformID.Win32NT or PlatformID.Win32S or PlatformID.Win32Windows)
        {
            Clipboard = new WindowsClipboard ();
        }
        else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
        {
            Clipboard = new MacOSXClipboard ();
        }
        else if (PlatformDetection.IsWSLPlatform ())
        {
            Clipboard = new WSLClipboard ();
        }

        // Clipboard is set to FakeClipboard at initialization
    }

    /// <summary>Gets the location and size of the terminal screen.</summary>
    public Rectangle Screen
    {
        get
        {
            //if (Application.RunningUnitTests && _output is WindowsConsoleOutput or NetOutput)
            //{
            //    // In unit tests, we don't have a real output, so we return an empty rectangle.
            //    return Rectangle.Empty;
            //}

            return new (0, 0, OutputBuffer.Cols, OutputBuffer.Rows);
        }
    }

    /// <summary>
    ///     Sets the screen size for testing purposes. Only supported by FakeDriver.
    /// </summary>
    /// <param name="width">The new width in columns.</param>
    /// <param name="height">The new height in rows.</param>
    /// <exception cref="NotSupportedException">Thrown when called on non-FakeDriver instances.</exception>
    public virtual void SetScreenSize (int width, int height)
    {
        OutputBuffer.SetSize (width, height);
        _output.SetSize (width, height);
        SizeChanged?.Invoke (this, new (new (width, height)));
    }

    /// <summary>
    ///     Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
    ///     to.
    /// </summary>
    /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
    public Region? Clip
    {
        get => OutputBuffer.Clip;
        set => OutputBuffer.Clip = value;
    }

    /// <summary>Get the operating system clipboard.</summary>
    public IClipboard? Clipboard { get; private set; } = new FakeClipboard ();

    /// <summary>
    ///     Gets the column last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
    ///     <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
    /// </summary>
    public int Col => OutputBuffer.Col;

    /// <summary>The number of columns visible in the terminal.</summary>
    public int Cols
    {
        get => OutputBuffer.Cols;
        set => OutputBuffer.Cols = value;
    }

    /// <summary>
    ///     The contents of the application output. The driver outputs this buffer to the terminal.
    ///     <remarks>The format of the array is rows, columns. The first index is the row, the second index is the column.</remarks>
    /// </summary>
    public Cell [,]? Contents
    {
        get => OutputBuffer.Contents;
        set => OutputBuffer.Contents = value;
    }

    /// <summary>The leftmost column in the terminal.</summary>
    public int Left
    {
        get => OutputBuffer.Left;
        set => OutputBuffer.Left = value;
    }

    /// <summary>
    ///     Gets the row last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
    ///     <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
    /// </summary>
    public int Row => OutputBuffer.Row;

    /// <summary>The number of rows visible in the terminal.</summary>
    public int Rows
    {
        get => OutputBuffer.Rows;
        set => OutputBuffer.Rows = value;
    }

    /// <summary>The topmost row in the terminal.</summary>
    public int Top
    {
        get => OutputBuffer.Top;
        set => OutputBuffer.Top = value;
    }

    // TODO: Probably not everyone right?

    /// <summary>Gets whether the <see cref="IDriver"/> supports TrueColor output.</summary>
    public bool SupportsTrueColor => true;

    // TODO: Currently ignored
    /// <summary>
    ///     Gets or sets whether the <see cref="IDriver"/> should use 16 colors instead of the default TrueColors.
    ///     See <see cref="Application.Force16Colors"/> to change this setting via <see cref="ConfigurationManager"/>.
    /// </summary>
    /// <remarks>
    ///     <para>
    ///         Will be forced to <see langword="true"/> if <see cref="IDriver.SupportsTrueColor"/> is
    ///         <see langword="false"/>, indicating that the <see cref="IDriver"/> cannot support TrueColor.
    ///     </para>
    /// </remarks>
    public bool Force16Colors
    {
        get => Application.Force16Colors || !SupportsTrueColor;
        set => Application.Force16Colors = value || !SupportsTrueColor;
    }

    /// <summary>
    ///     The <see cref="System.Attribute"/> that will be used for the next <see cref="AddRune(Rune)"/> or
    ///     <see cref="AddStr"/>
    ///     call.
    /// </summary>
    public Attribute CurrentAttribute
    {
        get => OutputBuffer.CurrentAttribute;
        set => OutputBuffer.CurrentAttribute = value;
    }

    /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
    /// <remarks>
    ///     <para>
    ///         When the method returns, <see cref="IDriver.Col"/> will be incremented by the number of columns
    ///         <paramref name="rune"/> required, even if the new column value is outside of the
    ///         <see cref="IDriver.Clip"/> or screen
    ///         dimensions defined by <see cref="IDriver.Cols"/>.
    ///     </para>
    ///     <para>
    ///         If <paramref name="rune"/> requires more than one column, and <see cref="IDriver.Col"/> plus the number
    ///         of columns
    ///         needed exceeds the <see cref="IDriver.Clip"/> or screen dimensions, the default Unicode replacement
    ///         character (U+FFFD)
    ///         will be added instead.
    ///     </para>
    /// </remarks>
    /// <param name="rune">Rune to add.</param>
    public void AddRune (Rune rune) { OutputBuffer.AddRune (rune); }

    /// <summary>
    ///     Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
    ///     convenience method that calls <see cref="IDriver.AddRune(System.Text.Rune)"/> with the <see cref="Rune"/>
    ///     constructor.
    /// </summary>
    /// <param name="c">Character to add.</param>
    public void AddRune (char c) { OutputBuffer.AddRune (c); }

    /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
    /// <remarks>
    ///     <para>
    ///         When the method returns, <see cref="IDriver.Col"/> will be incremented by the number of columns
    ///         <paramref name="str"/> required, unless the new column value is outside of the <see cref="IDriver.Clip"/>
    ///         or screen
    ///         dimensions defined by <see cref="IDriver.Cols"/>.
    ///     </para>
    ///     <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
    /// </remarks>
    /// <param name="str">String.</param>
    public void AddStr (string str) { OutputBuffer.AddStr (str); }

    /// <summary>Clears the <see cref="IDriver.Contents"/> of the driver.</summary>
    public void ClearContents ()
    {
        OutputBuffer.ClearContents ();
        ClearedContents?.Invoke (this, new MouseEventArgs ());
    }

    /// <summary>
    ///     Raised each time <see cref="IDriver.ClearContents"/> is called. For benchmarking.
    /// </summary>
    public event EventHandler<EventArgs>? ClearedContents;

    /// <summary>
    ///     Fills the specified rectangle with the specified rune, using <see cref="IDriver.CurrentAttribute"/>
    /// </summary>
    /// <remarks>
    ///     The value of <see cref="IDriver.Clip"/> is honored. Any parts of the rectangle not in the clip will not be
    ///     drawn.
    /// </remarks>
    /// <param name="rect">The Screen-relative rectangle.</param>
    /// <param name="rune">The Rune used to fill the rectangle</param>
    public void FillRect (Rectangle rect, Rune rune = default) { OutputBuffer.FillRect (rect, rune); }

    /// <summary>
    ///     Fills the specified rectangle with the specified <see langword="char"/>. This method is a convenience method
    ///     that calls <see cref="IDriver.FillRect(System.Drawing.Rectangle,System.Text.Rune)"/>.
    /// </summary>
    /// <param name="rect"></param>
    /// <param name="c"></param>
    public void FillRect (Rectangle rect, char c) { OutputBuffer.FillRect (rect, c); }

    /// <inheritdoc/>
    public virtual string GetVersionInfo ()
    {
        string type = InputProcessor.DriverName ?? throw new ArgumentNullException (nameof (InputProcessor.DriverName));

        return type;
    }

    /// <summary>Tests if the specified rune is supported by the driver.</summary>
    /// <param name="rune"></param>
    /// <returns>
    ///     <see langword="true"/> if the rune can be properly presented; <see langword="false"/> if the driver does not
    ///     support displaying this rune.
    /// </returns>
    public bool IsRuneSupported (Rune rune) { return Rune.IsValid (rune.Value); }

    /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
    /// <param name="rune">Used to determine if one or two columns are required.</param>
    /// <param name="col">The column.</param>
    /// <param name="row">The row.</param>
    /// <returns>
    ///     <see langword="false"/> if the coordinate is outside the screen bounds or outside of
    ///     <see cref="IDriver.Clip"/>.
    ///     <see langword="true"/> otherwise.
    /// </returns>
    public bool IsValidLocation (Rune rune, int col, int row) { return OutputBuffer.IsValidLocation (rune, col, row); }

    /// <summary>
    ///     Updates <see cref="IDriver.Col"/> and <see cref="IDriver.Row"/> to the specified column and row in
    ///     <see cref="IDriver.Contents"/>.
    ///     Used by <see cref="IDriver.AddRune(System.Text.Rune)"/> and <see cref="IDriver.AddStr"/> to determine
    ///     where to add content.
    /// </summary>
    /// <remarks>
    ///     <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
    ///     <para>
    ///         If <paramref name="col"/> or <paramref name="row"/> are negative or beyond  <see cref="IDriver.Cols"/>
    ///         and
    ///         <see cref="IDriver.Rows"/>, the method still sets those properties.
    ///     </para>
    /// </remarks>
    /// <param name="col">Column to move to.</param>
    /// <param name="row">Row to move to.</param>
    public void Move (int col, int row) { OutputBuffer.Move (col, row); }

    // TODO: Probably part of output

    /// <summary>Sets the terminal cursor visibility.</summary>
    /// <param name="visibility">The wished <see cref="CursorVisibility"/></param>
    /// <returns><see langword="true"/> upon success</returns>
    public bool SetCursorVisibility (CursorVisibility visibility)
    {
        _lastCursor = visibility;
        _output.SetCursorVisibility (visibility);

        return true;
    }

    /// <inheritdoc/>
    public bool GetCursorVisibility (out CursorVisibility current)
    {
        current = _lastCursor;

        return true;
    }

    /// <inheritdoc/>
    public void Suspend ()
    {
        // BUGBUG: This is all platform-specific and should not be implemented here.
        // BUGBUG: This needs to be in each platform's driver implementation.
        if (Environment.OSVersion.Platform != PlatformID.Unix)
        {
            return;
        }

        Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);

        try
        {
            Console.ResetColor ();
            Console.Clear ();

            //Disable alternative screen buffer.
            Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);

            //Set cursor key to cursor.
            Console.Out.Write (EscSeqUtils.CSI_ShowCursor);

            Platform.Suspend ();

            //Enable alternative screen buffer.
            Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
        }
        catch (Exception ex)
        {
            Logging.Error ($"Error suspending terminal: {ex.Message}");
        }

        Application.LayoutAndDraw ();


        Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
    }

    /// <summary>
    ///     Sets the position of the terminal cursor to <see cref="IDriver.Col"/> and
    ///     <see cref="IDriver.Row"/>.
    /// </summary>
    public void UpdateCursor () { _output.SetCursorPosition (Col, Row); }

    /// <summary>Initializes the driver</summary>
    public void Init () { throw new NotSupportedException (); }

    /// <summary>Ends the execution of the console driver.</summary>
    public void End ()
    {
        // TODO: Nope
    }

    /// <summary>Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.</summary>
    /// <remarks>Implementations should call <c>base.SetAttribute(c)</c>.</remarks>
    /// <param name="newAttribute">C.</param>
    /// <returns>The previously set Attribute.</returns>
    public Attribute SetAttribute (Attribute newAttribute)
    {
        Attribute currentAttribute = OutputBuffer.CurrentAttribute;
        OutputBuffer.CurrentAttribute = newAttribute;

        return currentAttribute;
    }

    /// <summary>Gets the current <see cref="Attribute"/>.</summary>
    /// <returns>The current attribute.</returns>
    public Attribute GetAttribute () { return OutputBuffer.CurrentAttribute; }

    /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="IDriver.KeyUp"/>.</summary>
    public event EventHandler<Key>? KeyDown;

    /// <summary>Event fired when a key is released.</summary>
    /// <remarks>
    ///     Drivers that do not support key release events will fire this event after <see cref="IDriver.KeyDown"/>
    ///     processing is
    ///     complete.
    /// </remarks>
    public event EventHandler<Key>? KeyUp;

    /// <summary>Event fired when a mouse event occurs.</summary>
    public event EventHandler<MouseEventArgs>? MouseEvent;

    /// <summary>
    ///     Provide proper writing to send escape sequence recognized by the <see cref="IDriver"/>.
    /// </summary>
    /// <param name="ansi"></param>
    public void WriteRaw (string ansi) { _output.Write (ansi); }

    /// <inheritdoc/>
    public void EnqueueKeyEvent (Key key)
    {
        InputProcessor.EnqueueKeyDownEvent (key);
    }

    /// <summary>
    ///     Queues the specified ANSI escape sequence request for execution.
    /// </summary>
    /// <param name="request">The ANSI request to queue.</param>
    /// <remarks>
    ///     The request is sent immediately if possible, or queued for later execution
    ///     by the <see cref="AnsiRequestScheduler"/> to prevent overwhelming the console.
    /// </remarks>
    public void QueueAnsiRequest (AnsiEscapeSequenceRequest request) { _ansiRequestScheduler.SendOrSchedule (this, request); }

    /// <summary>
    ///     Gets the <see cref="AnsiRequestScheduler"/> instance used by this driver.
    /// </summary>
    /// <returns>The ANSI request scheduler.</returns>
    public AnsiRequestScheduler GetRequestScheduler () { return _ansiRequestScheduler; }

    /// <inheritdoc/>
    public void Refresh ()
    {
        // No need we will always draw when dirty
    }

    public string? GetName ()
    {
        return InputProcessor.DriverName?.ToLowerInvariant ();
    }
}
