package getsvc

import (
	"context"

	"git.frostfs.info/TrueCloudLab/frostfs-node/internal/logs"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/client"
	"go.uber.org/zap"
)

func (exec *execCtx) executeOnContainer(ctx context.Context) {
	if exec.isLocal() {
		exec.log.Debug(logs.GetReturnResultDirectly)
		return
	}

	lookupDepth := exec.netmapLookupDepth()

	exec.log.Debug(logs.TryingToExecuteInContainer,
		zap.Uint64("netmap lookup depth", lookupDepth),
	)

	// initialize epoch number
	ok := exec.initEpoch()
	if !ok {
		return
	}

	for {
		if exec.processCurrentEpoch(ctx) {
			break
		}

		// check the maximum depth has been reached
		if lookupDepth == 0 {
			break
		}

		lookupDepth--

		// go to the previous epoch
		exec.curProcEpoch--
	}
}

func (exec *execCtx) processCurrentEpoch(ctx context.Context) bool {
	exec.log.Debug(logs.ProcessEpoch,
		zap.Uint64("number", exec.curProcEpoch),
	)

	traverser, ok := exec.generateTraverser(exec.address())
	if !ok {
		return true
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	exec.status = statusUndefined

	for {
		addrs := traverser.Next()
		if len(addrs) == 0 {
			exec.log.Debug(logs.NoMoreNodesAbortPlacementIteration)

			return false
		}

		for i := range addrs {
			select {
			case <-ctx.Done():
				exec.log.Debug(logs.InterruptPlacementIterationByContext,
					zap.String("error", ctx.Err().Error()),
				)

				return true
			default:
			}

			// TODO: #1142 consider parallel execution
			// TODO: #1142 consider optimization: if status == SPLIT we can continue until
			//  we reach the best result - split info with linking object ID.
			var info client.NodeInfo

			client.NodeInfoFromNetmapElement(&info, addrs[i])

			if exec.processNode(ctx, info) {
				exec.log.Debug(logs.GetCompletingTheOperation)
				return true
			}
		}
	}
}