unit Myc.Fmx.AstEditor.Handlers.Lists;

interface

uses
    System.SysUtils,
    System.Generics.Collections,
    Myc.Ast,
    Myc.Ast.Nodes,
    Myc.Fmx.AstEditor.Render,
    Myc.Fmx.AstEditor.Node;

type
    // Unified handler for all list-like structures (Parameters, Arguments, Vectors, and Pipe-Inputs)
    TTupleHandler = class(TBaseNodeHandler<ITupleNode>)
    private
        FChildNodes: TList<TAstViewNode>;
    public
        constructor Create(const ANode: ITupleNode);
        destructor Destroy; override;
        procedure BuildUI(OwnerNode: TAstViewNode); override;
        function ReconstructAst(OwnerNode: TAstViewNode): IAstNode; override;
    end;

implementation

uses
    System.UITypes;

{ TTupleHandler }

constructor TTupleHandler.Create(const ANode: ITupleNode);
begin
    inherited Create(ANode);
    FChildNodes := TList<TAstViewNode>.Create;
end;

destructor TTupleHandler.Destroy;
begin
    FChildNodes.Free;
    inherited;
end;

procedure TTupleHandler.BuildUI(OwnerNode: TAstViewNode);
var
    visu: IAstVisualizer;
    i: Integer;
    childView: TAstViewNode;
    lbl: TTextNode;
    elements: TArray<IAstNode>;
begin
    // Tuples act as lists, using horizontal flow (e.g. [1 2 3] or [[src [:sel]]])
    OwnerNode.Frameless := True;
    OwnerNode.Orientation := loHorizontal;
    OwnerNode.Alignment := laCenter;

    // Opening Bracket
    lbl := OwnerNode.AddLabel(OwnerNode, '[');
    lbl.FontSettings.Font.Style := [TFontStyle.fsBold];
    lbl.Color := $FFBBBBBB;

    visu := OwnerNode.Visualizer.Clone(OwnerNode, OwnerNode.Visualizer.ExprDepth);

    // Optimization: Access Elements array directly
    elements := FNode.Elements;

    for i := 0 to High(elements) do
    begin
        // Standard spacing between elements
        if i > 0 then
            OwnerNode.AddLabel(OwnerNode, ' ');

        childView := visu.CallAccept(elements[i]);
        FChildNodes.Add(childView);
    end;

    // Visual hint for empty tuples
    if Length(elements) = 0 then
    begin
        OwnerNode.AddLabel(OwnerNode, ' '); // spacer
    end;

    // Closing Bracket
    lbl := OwnerNode.AddLabel(OwnerNode, ']');
    lbl.FontSettings.Font.Style := [TFontStyle.fsBold];
    lbl.Color := $FFBBBBBB;
end;

function TTupleHandler.ReconstructAst(OwnerNode: TAstViewNode): IAstNode;
var
    newElements: TArray<IAstNode>;
    i: Integer;
begin
    SetLength(newElements, FChildNodes.Count);
    for i := 0 to FChildNodes.Count - 1 do
        newElements[i] := FChildNodes[i].CreateAst;

    Result := TAst.Tuple(FNode.Identity, newElements, FNode.StaticType);
end;

end.
