import Validator from "./Validators/Validator";
import EventHandler from "../Utility/EventHandler";

export default abstract class DataType<T>{
    protected validators: Validator[] = [];

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

    public addValidator(...validators: Validator[]): void{
        this.validators.push(...validators);
        validators.forEach(
            validator =>
                validator.onChange.add(() => this.onChange.emit(null))
        );
    }

    public validate(value: T|null): true|string[]{
        let isValid: boolean = true;
        let messages: string[] = [];

        this.validators.forEach(
            validator => {
                let result = validator.validate(value);
                if(result !== true){
                    isValid = false;
                    messages.push(result);
                }
            }
        );

        return isValid ? true : messages;
    }

    public abstract sanitize(value: any): T|null|undefined;
}