import DataType from "../DataType";

export default class ArrayType<T> extends DataType<T[]>{
    constructor(
        protected subDataType: DataType<T>
    ){
        super();
        this.subDataType.onChange.add(() => this.onChange.emit(null));
    }

    public sanitize(value: any): T[]|null|undefined {
        if (value === null || value === undefined) return value;
        if (!Array.isArray(value)) {
            console.warn("Value is not an array");
            console.warn(value);
            throw new Error("Value is not an array");
        }
        value = value.map(v => this.subDataType.sanitize(v));
        return value;
    }

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

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

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

        return isValid ? true : messages;
    }
}