package query

import (
	"fmt"
	"git.nspix.com/golang/rest/internal/empty"
	"strings"
)

type Condition struct {
	Field    string      `json:"field"`
	Value    interface{} `json:"value"`
	Operator string      `json:"operator"`
}

func buildConditions(operator string, filter bool, conds ...*Condition) (condition string, params []interface{}) {
	var (
		sb strings.Builder
	)
	params = make([]interface{}, 0)
	for _, cond := range conds {
		if filter {
			if empty.Is(cond.Value) {
				continue
			}
		}
		if cond.Operator == "" {
			cond.Operator = "="
		}
		switch strings.ToUpper(cond.Operator) {
		case "=", "<>", ">", "<", ">=", "<=", "!=":
			if sb.Len() > 0 {
				sb.WriteString(" " + operator + " ")
			}
			if cond.Operator == "=" && cond.Value == nil {
				sb.WriteString(cond.Field + " IS NULL")
			} else {
				sb.WriteString(cond.Field + " " + cond.Operator + " ?")
				params = append(params, cond.Value)
			}
		case "LIKE":
			if sb.Len() > 0 {
				sb.WriteString(" " + operator + " ")
			}
			cond.Value = fmt.Sprintf("%%%s%%", cond.Value)
			sb.WriteString(cond.Field + " LIKE ?")
			params = append(params, cond.Value)
		case "IN":
			if sb.Len() > 0 {
				sb.WriteString(" " + operator + " ")
			}
			sb.WriteString(cond.Field + " IN (" + fmt.Sprint(cond.Value) + ")")
		case "BETWEEN":

		default:
			continue
		}
	}
	condition = sb.String()
	return
}

func NewCondition(field string, value interface{}) *Condition {
	return &Condition{
		Field:    field,
		Value:    value,
		Operator: "=",
	}
}

func NewConditionWithOperator(operator, field string, value interface{}) *Condition {
	cond := &Condition{
		Field:    field,
		Value:    value,
		Operator: operator,
	}
	return cond
}
