package odbcmql

import (
	"context"
	"fmt"
	"strings"
	"time"

	odb "git.wecise.com/wecise/odb-go/odb"
	"gitee.com/wecisecode/util/cast"
)

func ODBCQueryWithTimeoutDo(ctx context.Context, qmeta odb.QueryMeta, timeout time.Duration, mql string, values ...interface{}) (*odb.Result, error) {
	var q odb.Query
	if mql[0] == '#' {
		q = ODBC.Search(mql)
	} else if len(mql) >= 4 && strings.ToLower(mql[:4]) == "cql:" {
		q = ODBC.QueryCql(strings.TrimSpace(mql[4:]), values...)
	} else if len(mql) >= 4 && strings.ToLower(mql[:4]) == "sql:" {
		q = ODBC.QuerySql(strings.TrimSpace(mql[4:]), values...)
	} else if len(mql) >= 4 && strings.ToLower(mql[:4]) == "cmd:" {
		args := strings.Split(strings.TrimSpace(mql[4:]), " ")
		vals := []any{}
		for _, arg := range args {
			arg = strings.TrimSpace(arg)
			if arg != "" {
				vals = append(vals, arg)
			}
		}
		vals = append(vals, values...)
		if len(vals) == 0 {
			return nil, fmt.Errorf("odbc cmd is empty")
		}
		cmd := cast.ToString(vals[0])
		vals = vals[1:]
		q = ODBC.Command(cmd, vals...)
	} else {
		q = ODBC.Query(mql, values...)
	}
	return q.WithContext(ctx).WithMeta(qmeta).WithTimeout(timeout).Do()
}
