// This is for things that get us out of statement blocks: break, continue,
// return.

package cst

import (
	"fmt"

	"github.com/johnkerl/miller/v6/pkg/lib"
	"github.com/johnkerl/miller/v6/pkg/runtime"

	"github.com/johnkerl/pgpg/go/lib/pkg/asts"
)

type BreakNode struct {
}

func (root *RootNode) BuildBreakNode(astNode *asts.ASTNode) (*BreakNode, error) {
	lib.InternalCodingErrorIf(astNode.Type != asts.NodeType(NodeTypeBreakStatement))
	lib.InternalCodingErrorIf(astNode.Children == nil)
	lib.InternalCodingErrorIf(len(astNode.Children) != 0)

	return &BreakNode{}, nil
}

func (node *BreakNode) Execute(state *runtime.State) (*BlockExitPayload, error) {
	return &BlockExitPayload{
		BLOCK_EXIT_BREAK,
		nil,
	}, nil
}

type ContinueNode struct {
}

func (root *RootNode) BuildContinueNode(astNode *asts.ASTNode) (*ContinueNode, error) {
	lib.InternalCodingErrorIf(astNode.Type != asts.NodeType(NodeTypeContinueStatement))
	lib.InternalCodingErrorIf(astNode.Children == nil)
	lib.InternalCodingErrorIf(len(astNode.Children) != 0)

	return &ContinueNode{}, nil
}

func (node *ContinueNode) Execute(state *runtime.State) (*BlockExitPayload, error) {
	return &BlockExitPayload{
		BLOCK_EXIT_CONTINUE,
		nil,
	}, nil
}

type ReturnNode struct {
	returnValueExpression IEvaluable
}

func (root *RootNode) BuildReturnNode(astNode *asts.ASTNode) (*ReturnNode, error) {
	lib.InternalCodingErrorIf(astNode.Type != asts.NodeType(NodeTypeReturnStatement))
	lib.InternalCodingErrorIf(astNode.Children == nil)
	if len(astNode.Children) == 0 {
		return &ReturnNode{returnValueExpression: nil}, nil
	} else if len(astNode.Children) == 1 {
		returnValueExpression, err := root.BuildEvaluableNode(astNode.Children[0])
		if err != nil {
			return nil, err
		}
		return &ReturnNode{returnValueExpression: returnValueExpression}, nil
	}
	lib.InternalCodingErrorIf(true)
	return nil, fmt.Errorf("internal coding error: statement should not be reached")
}

func (node *ReturnNode) Execute(state *runtime.State) (*BlockExitPayload, error) {
	if node.returnValueExpression == nil {
		return &BlockExitPayload{
			BLOCK_EXIT_RETURN_VOID,
			nil,
		}, nil
	} else {
		// The return value can be of type MT_ERROR but we do not use Go-level error return here.
		returnValue := node.returnValueExpression.Evaluate(state)
		return &BlockExitPayload{
			BLOCK_EXIT_RETURN_VALUE,
			returnValue.Copy(),
		}, nil
	}
}
