using CommunityToolkit.Mvvm.ComponentModel;

namespace DodoSSH.Client.Shell.ViewModels;

/// <summary>
/// How far along a tab's connection is.
/// </summary>
/// <remarks>
/// A tab exists before its session does — see <see cref="TerminalTabViewModel"/> — so "is there a pane
/// behind this" is a question the strip and the window both have to be able to ask. Three states rather
/// than a nullable session id, because <see cref="Failed"/> and <see cref="Connecting"/> are both "no
/// session" and only one of them is still worth waiting for.
/// </remarks>
internal enum TerminalTabState
{
    /// <summary>The connection is being made. There is no pane yet.</summary>
    Connecting = 0,

    /// <summary>A session was opened, and the renderer has a pane for it.</summary>
    Open = 1,

    /// <summary>The connection did not happen. There is no pane, and there never will be for this tab.</summary>
    Failed = 2,
}

/// <summary>
/// One terminal, as a tab: from the moment connecting starts to the moment the tab is closed.
/// </summary>
/// <remarks>
/// <para>
/// A tab is a session id and a handful of strings — the address, and now the three connection facts the
/// status bar draws beside CONNECTED. It holds no terminal and owns nothing: the pane, its scrollback and the
/// shell behind it all live in the renderer and in <c>TerminalWorkspace</c>, and selecting a tab is one frame
/// telling the page which pane to show. That is what makes tabs cheap here — the expensive object is the
/// WebView, and there is one of those however many tabs are open.
/// </para>
/// <para>
/// <b>A tab starts before its session does.</b> Connecting is a network round trip that can take as long as
/// a DNS lookup and a handshake take, and the strip is where that is admitted to: the tab appears at the
/// moment the user asks for it, carrying <see cref="Status"/> instead of a pane, and becomes a real terminal
/// when <see cref="Opened"/> is called. Nothing about the rest of the application waits for that — which is
/// the point, because the alternative is a window that does nothing visible for ten seconds.
/// </para>
/// <para>
/// <b>Tabs belong to the shell, not to the vault.</b> Locking disposes the vault and every key it held, and
/// deliberately leaves shells running — so a tab list rebuilt per unlock would lose track of sessions that
/// are still connected, and the unlock screen's count of them would be the only place they appeared. The
/// shell outlives every lock, and so does this.
/// </para>
/// </remarks>
internal sealed partial class TerminalTabViewModel : ObservableObject
{
    /// <summary>A tab for a connection that is still being made.</summary>
    /// <param name="label">The host's name, as the vault has it.</param>
    /// <param name="address">Who this will be logged in as, and where.</param>
    internal TerminalTabViewModel(string label, string address)
    {
        Label = label;
        Address = address;
        status = "connecting…";
        isLive = false;
    }

    /// <summary>A tab for a session that is already open.</summary>
    /// <param name="sessionId">Identifies this terminal to the renderer.</param>
    /// <param name="label">The host's name, as the vault has it.</param>
    /// <param name="address">Who this is logged in as, and where.</param>
    internal TerminalTabViewModel(uint sessionId, string label, string address)
        : this(label, address)
    {
        SessionId = sessionId;
        state = TerminalTabState.Open;
        status = string.Empty;
        isLive = true;
    }

    /// <summary>
    /// Identifies this terminal to the renderer, or zero while there is no session.
    /// </summary>
    /// <remarks>
    /// Zero is not a session id the workspace ever hands out — it counts from one — so it can stand for
    /// "not connected yet" without a nullable that every caller would have to unwrap. <see cref="HasSession"/>
    /// is what the window asks rather than this.
    /// </remarks>
    internal uint SessionId { get; private set; }

    internal string Label { get; }

    /// <summary>The account and endpoint, for the pane header and the status bar.</summary>
    internal string Address { get; }

    /// <summary>
    /// When the session behind this tab opened, for the status bar's elapsed timer — or null while there is
    /// none.
    /// </summary>
    /// <remarks>
    /// Set by <c>MainWindowViewModel</c> from its own clock at the same moment it calls <see cref="Opened"/>
    /// or constructs a tab that already carries a session id, rather than read here from
    /// <see cref="TimeProvider.System"/> directly — a view model with its own notion of "now" is a second
    /// clock the shell's tests would have no way to control. Left on a tab whose session has since ended:
    /// the pane still holds the scrollback, and "how long that shell ran" stays a true fact about it after it
    /// stops being live.
    /// </remarks>
    internal DateTimeOffset? StartedAt { get; set; }

    /// <summary>
    /// The negotiated server-to-client cipher, for the status bar — or null while there is no session.
    /// </summary>
    /// <remarks>
    /// Set alongside <see cref="StartedAt"/>, from the same event, and kept for the same reason: a dead tab's
    /// pane still holds the scrollback of a session that really did negotiate this cipher, and clearing the
    /// fact when the shell ends would not make it less true of what is on screen.
    /// </remarks>
    internal string? Cipher { get; set; }

    /// <summary>The accepted host key's algorithm, e.g. <c>ssh-ed25519</c> — or null while there is no session.</summary>
    /// <remarks>See <see cref="Cipher"/>; set and kept the same way, for the same reason.</remarks>
    internal string? HostKeyAlgorithm { get; set; }

    /// <summary>
    /// The display name of the key or credential that authenticated, or null when a typed password did, or
    /// null while there is no session.
    /// </summary>
    /// <remarks>
    /// Three different reasons collapse to the same null, and that is deliberate: nothing downstream needs to
    /// tell a session with no identity to name apart from a tab that has not opened one yet — both mean the
    /// status bar shows the host-key algorithm alone, with no ` · name` after it.
    /// </remarks>
    internal string? IdentityLabel { get; set; }

    /// <inheritdoc cref="TerminalTabState" />
    [ObservableProperty]
    private TerminalTabState state;

    /// <summary>
    /// What this tab has to say for itself while it has no pane.
    /// </summary>
    /// <remarks>
    /// Empty once a session is open, because from then on the pane speaks for itself — anything written here
    /// would be a second, staler account of what the terminal is already showing.
    /// </remarks>
    [ObservableProperty]
    private string status;

    /// <summary>
    /// Whether the shell behind this tab is still running.
    /// </summary>
    /// <remarks>
    /// Cleared when the workspace says the session ended, never inferred from the tab being closed — closing
    /// a tab removes it, and a removed tab has nothing left to report. A dead tab is kept on purpose: its
    /// pane still holds the scrollback, and the last thing the remote said is usually why the shell ended.
    /// </remarks>
    [ObservableProperty]
    private bool isLive;

    /// <summary>
    /// Whether this is the tab whose pane is showing.
    /// </summary>
    /// <remarks>
    /// A flag on the tab as well as a selection on the shell, because the strip is an
    /// <c>ItemsControl</c> of buttons rather than a control that owns a selection — and a button has no
    /// <c>:selected</c> pseudo-class to style against. The shell writes it; nothing else does.
    /// </remarks>
    [ObservableProperty]
    private bool isSelected;

    /// <summary>
    /// Whether this tab is the thing the window is currently showing.
    /// </summary>
    /// <remarks>
    /// Not the same question as <see cref="IsSelected"/>, and the strip has to ask this one. The selection
    /// survives navigating away — that is what makes the strip a way back to a terminal rather than a way to
    /// lose it — so a tab that stayed lit while preferences filled the window would be a second "you are
    /// here" mark pointing at something nobody can see. The rail's own entries make exactly this distinction;
    /// see <c>MainWindowViewModel.IsHostsShowing</c>. The shell writes it, from the selection and the surface
    /// together.
    /// </remarks>
    [ObservableProperty]
    private bool isShowing;

    /// <summary>Whether there is a pane behind this tab.</summary>
    internal bool HasSession => State is TerminalTabState.Open;

    /// <summary>Whether this tab is still waiting on a connection.</summary>
    internal bool IsConnecting => State is TerminalTabState.Connecting;

    /// <summary>Whether this tab is a connection that never happened.</summary>
    internal bool IsFailed => State is TerminalTabState.Failed;

    /// <summary>Takes ownership of the session that has just opened for this tab.</summary>
    internal void Opened(uint sessionId)
    {
        SessionId = sessionId;
        Status = string.Empty;
        IsLive = true;
        State = TerminalTabState.Open;
    }

    /// <summary>
    /// Records that the connection this tab was opened for did not happen.
    /// </summary>
    /// <remarks>
    /// The tab stays, and that is deliberate: connecting no longer blocks the window, so by the time a
    /// refusal arrives the user is quite likely looking at something else — and a tab that vanished would
    /// take the only account of what went wrong with it. It is closed the way every other tab is.
    /// </remarks>
    internal void Failed(string reason)
    {
        Status = reason;
        IsLive = false;
        State = TerminalTabState.Failed;
    }

    partial void OnStateChanged(TerminalTabState value)
    {
        OnPropertyChanged(nameof(HasSession));
        OnPropertyChanged(nameof(IsConnecting));
        OnPropertyChanged(nameof(IsFailed));
    }
}
