package core

import (
	"git.akyoto.dev/cli/q/src/errors"
	"git.akyoto.dev/cli/q/src/expression"
	"git.akyoto.dev/cli/q/src/scope"
	"git.akyoto.dev/cli/q/src/token"
)

// Define defines a new variable.
func (f *Function) Define(leaf *expression.Expression) (*scope.Variable, error) {
	name := leaf.Token.Text(f.File.Bytes)
	variable := f.VariableByName(name)

	if variable != nil {
		return nil, errors.New(&errors.VariableAlreadyExists{Name: name}, f.File, leaf.Token.Position)
	}

	uses := token.Count(f.Body, f.File.Bytes, token.Identifier, name) - 1

	if uses == 0 {
		return nil, errors.New(&errors.UnusedVariable{Name: name}, f.File, leaf.Token.Position)
	}

	variable = &scope.Variable{
		Name:     name,
		Register: f.NewRegister(),
		Alive:    uses,
	}

	return variable, nil
}