package engine

import (
	"errors"

	"github.com/pingcap-inc/checker/proto"
	"github.com/sirupsen/logrus"
)

type CheckLine interface {
	Check(data proto.SourceData, rule string) error
}

const resultlen int = 10

type RuleCheck struct {
	Result chan map[string]proto.RuleResult
	//close       chan struct{}
}

func (c *RuleCheck) Init() {
	c.Result = make(chan map[string]proto.RuleResult, resultlen)
}

func (c *RuleCheck) GetResultChan() <-chan map[string]proto.RuleResult {
	return c.Result
}

func (c *RuleCheck) Check(data proto.SourceDataV2, rule proto.RuleSet) error {
	defer close(c.Result)
	for component, configs := range data.NodesData {
		configRule, ok := rule[component]
		if !ok {
			logrus.Error("no such component rule, ", component)
			return errors.New("no rule found")
		}
		ruleSpread := make(map[string]proto.RuleResult) // todo check pointer
		for _, config := range configs {
			checkunit := &Rule{}
			err := checkunit.Mapping(config, configRule, proto.DeviceData{}, ruleSpread) // todo delete device
			if err != nil {
				logrus.Error("mapping failed", err)
				return err
			}
		}
		c.Result <- ruleSpread
	}
	return nil
}
