<?php

/**
 * Vala-IR expression for an instance method call such as value.concat(other).
 */
final class ValaIrMethodCallExpression
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private object $receiver;
    private string $methodName;
    private array $args;

    /**
     * Create an instance method call expression.
     */
    public function __construct(int $startLine, int $endLine, array $comments, object $receiver, string $methodName, array $args)
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->receiver = $receiver;
        $this->methodName = $methodName;
        $this->args = $args;
    }

    /**
     * Return a copy of this method call with replaced receiver and arguments.
     *
     * @param object $receiver Replacement receiver expression.
     * @param object[] $args Replacement argument expressions.
     */
    public function withReceiverAndArgs(object $receiver, array $args): self
    {
        return new self($this->startLine, $this->endLine, $this->comments, $receiver, $this->methodName, $args);
    }

    /** Return this method call's receiver expression. */
    public function receiver(): object
    {
        return $this->receiver;
    }

    /** Return this method call's argument nodes. */
    public function args(): array
    {
        return $this->args;
    }

    /**
     * Convert to a plain array for debugging/export.
     */
    public function toArray(): array
    {
        return [
            'kind' => 'MethodCallExpression',
            'startLine' => $this->startLine,
            'endLine' => $this->endLine,
            'comments' => array_map(static fn (ValaIrComment $comment): array => $comment->toArray(), $this->comments),
            'receiver' => method_exists($this->receiver, 'toArray') ? $this->receiver->toArray() : ['kind' => get_debug_type($this->receiver)],
            'methodName' => $this->methodName,
            'args' => array_map(
                static fn (object $arg): array => method_exists($arg, 'toArray') ? $arg->toArray() : ['kind' => get_debug_type($arg)],
                $this->args,
            ),
        ];
    }
}
