import Condition from "../../Conditions/Condition";
import EventHandler from "../../Utility/EventHandler";

export default abstract class Validator {
    public errorMessage: string = "";
    public checkName: string = "";
    protected conditions: Condition[] = [];
    protected _isValid: boolean = true;

    public onChange: EventHandler<null> = new EventHandler();

    protected constructor(params: Partial<Validator> = {}) {
        Object.assign(this, params);
    }

    public abstract validate(value: any): true|string;

    public addConditions(...conditions: Condition[]): void{
        this.conditions.push(...conditions);
        conditions.forEach(
            condition =>
                condition.onChange.add((valid: boolean) => this.checkConditions(valid))
        );
    }

    public checkConditions(valid:boolean|null = null): void{
        if( this._isValid === valid) return;
        if( valid === false ){
            this.isValid = false;
            return;
        }

        this.isValid = this.conditions.every(condition => condition.check());
    }

    protected set isValid(value: boolean){
        if( this._isValid === value) return;
        this._isValid = value;
        this.onChange.emit(null);
    }
}