package com.inspect.guideline;

import com.inspect.base.core.exception.ServiceException;
import com.inspect.guideline.calculate.GuidelineCalculator;
import com.inspect.guideline.constant.DefectTypeEnum;
import com.inspect.guideline.constant.PatrolGuidelineCollection;
import com.inspect.guideline.domain.PatrolGuideline;
import com.inspect.guideline.domain.PatrolGuidelineRule;

import java.util.Iterator;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.springframework.stereotype.Component;

@Component
public class GuidelineEngineer {
    public PatrolGuidelineRule parse(Long guidelineId, double weatherT, double currentT, double... difTs) throws ScriptException {
        double rtd = GuidelineCalculator.calRdt(weatherT, currentT, difTs);
        double td = GuidelineCalculator.calDt(currentT, difTs);
        return this.parse(guidelineId, currentT, rtd, td);
    }

    public PatrolGuidelineRule parse(Long guidelineId, double t, double rtd, double td) throws ScriptException {
        PatrolGuideline patrolGuideline = PatrolGuidelineCollection.INSTANCE.get(guidelineId);
        if (patrolGuideline == null) {
            throw new ServiceException("664导则：无相关导则");
        } else {
            List<PatrolGuidelineRule> patrolGuidelineRules = patrolGuideline.getPatrolGuidelineRules();
            Iterator<PatrolGuidelineRule> iterator = patrolGuidelineRules.iterator();
            PatrolGuidelineRule patrolGuidelineRule;
            do {
                if (!iterator.hasNext()) {
                    return new PatrolGuidelineRule(DefectTypeEnum.REGULAR.getType(), DefectTypeEnum.REGULAR.getName());
                }

                patrolGuidelineRule = iterator.next();
            } while (!this.parse(patrolGuidelineRule, t, rtd, td));

            return patrolGuidelineRule;
        }
    }

    private boolean parse(PatrolGuidelineRule patrolGuidelineRule, double t, double rtd, double td) throws ScriptException {
        String ruleCondition = patrolGuidelineRule.getRuleCondition();
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        engine.put("rtd", rtd);
        engine.put("td", td);
        engine.put("t", t);
        Object eval = engine.eval(ruleCondition);
        return (Boolean) eval;
    }
}
