import { Rule } from "../../../../../core/model/dataset-profile-definition/rule";
import { VisibilityRule } from "./visibility-rule";

export class VisibilityRulesContext {

	public rules: Array<VisibilityRule> = new Array();

	constructor() { }

	public getRulesFromKey(id: string): VisibilityRule {

		for (let i = 0; i < this.rules.length; i++) {
			if (id === this.rules[i].targetControlId) { return this.rules[i]; }
		}
		return null;
	}

	public buildVisibilityRuleContext(items: Array<Rule>) {
		items.forEach(item => {
			this.addToVisibilityRulesContext(item);
		});
	}

	public addToVisibilityRulesContext(item: Rule): void {
		for (let i = 0; i < this.rules.length; i++) {
			if (this.rules[i].targetControlId === item.targetField) {

				const newRule = { sourceControlId: item.sourceField, sourceControlValue: item.requiredValue };
				const ruleExists  = this.rules[i].sourceVisibilityRules.find(x =>{
					return Object.keys(x).reduce((exact, key)=>{
						if(!exact) return false;
						return x[key] === newRule[key];
					},true);
				})

				if(!ruleExists){
					this.rules[i].sourceVisibilityRules.push(newRule);
				}

				return;
			}
		}
		const newVisibilityRuleArray = [({ sourceControlId: item.sourceField, sourceControlValue: item.requiredValue })];
		this.rules.push({ targetControlId: item.targetField, sourceVisibilityRules: newVisibilityRuleArray });
		return;
	}
}
