package cmdpacks

import (
	"context"
	"lmika.dev/cmd/dynamo-browse/internal/common/ui/commandctrl"
	"lmika.dev/cmd/dynamo-browse/internal/dynamo-browse/controllers"
	"lmika.dev/cmd/dynamo-browse/internal/dynamo-browse/models"
	"github.com/pkg/errors"
)

type tablePVar struct {
	state *controllers.State
}

func (rs tablePVar) Get(ctx context.Context) (any, error) {
	return newTableProxy(rs.state.ResultSet().TableInfo), nil
}

type resultSetPVar struct {
	state          *controllers.State
	readController *controllers.TableReadController
}

func (rs resultSetPVar) Get(ctx context.Context) (any, error) {
	return newResultSetProxy(rs.state.ResultSet()), nil
}

func (rs resultSetPVar) Set(ctx context.Context, value any) error {
	rsVal, ok := value.(SimpleProxy[*models.ResultSet])
	if !ok {
		return errors.New("new value to @resultset is nil or not a result set")
	}

	msg := rs.readController.SetResultSet(rsVal.value)
	commandctrl.PostMsg(ctx, msg)
	return nil
}

type itemPVar struct {
	state *controllers.State
}

func (rs itemPVar) Get(ctx context.Context) (any, error) {
	selItem, ok := commandctrl.SelectedItemIndex(ctx)
	if !ok {
		return nil, errors.New("no item selected")
	}
	return itemProxy{rs.state.ResultSet(), selItem, rs.state.ResultSet().Items()[selItem]}, nil
}

func (rs itemPVar) Set(ctx context.Context, value any) error {
	rsVal, ok := value.(itemProxy)
	if !ok {
		return errors.New("new value to @item is not an item")
	}

	if msg := commandctrl.SetSelectedItemIndex(ctx, rsVal.idx); msg != nil {
		commandctrl.PostMsg(ctx, msg)
	}

	return nil
}
