package grmi

import (
	"strings"
)

type Condition struct {
	*Paging
	Items         map[string]ConditionItem
	OrderByFields []Field
}

func NewCondition(items map[string]ConditionItem, paging *Paging) Condition {
	orderByFields := make([]Field, 0, 10)
	conditionItems := make(map[string]ConditionItem, 0)
	for key, item := range items {
		if item.OrderBy {
			orderByFields = append(orderByFields, item.Field)
		}
		valueParser, ok := valueParsers[item.Field.GoType]
		if ok {
			item.valueParser = valueParser
			conditionItems[key] = item
		}
	}
	return Condition{Items: conditionItems, Paging: paging, OrderByFields: orderByFields}
}

func (self *Condition) BuildPredicates(urlParameters map[string]string) ([]Predicate, error) {
	predicates := make([]Predicate, 0, len(urlParameters))
	for name, value := range urlParameters {
		item, ok := self.Items[strings.ToLower(name)]
		if !ok {
			continue
		}
		predicateValue, err := item.valueParser(value)
		if err != nil {
			return nil, NewRequestError(err)
		}
		predicates = append(predicates, item.NewPredicate(item.PredicateType, predicateValue))
	}
	return predicates, nil
}
