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);
		});
	}

	private addToVisibilityRulesContext(item: Rule): void {
		for (let i = 0; i < this.rules.length; i++) {
			if (this.rules[i].targetControlId === item.targetField) {
				this.rules[i].sourceVisibilityRules.push({ sourceControlId: item.sourceField, sourceControlValue: item.requiredValue });
				return;
			}
		}
		const newVisibilityRuleArray = [({ sourceControlId: item.sourceField, sourceControlValue: item.requiredValue })];
		this.rules.push({ targetControlId: item.targetField, sourceVisibilityRules: newVisibilityRuleArray });
		return;
	}
}
