import Validator from "../Validator";
import ValidatorFactory, {ValidatorConfig} from "../ValidatorFactory";

export default class RegexValidator extends Validator{
    public regex: string = '';

    public validate(value: any): true|string {
        if (!this._isValid) return true;
        if (typeof value === "string" && value.trim() === "") return true;
        if (typeof value === "string" && !(new RegExp(this.regex)).test(value.trim())) return this.errorMessage;
        return true;
    }

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

interface RegexValidatorConfig extends ValidatorConfig {
    type: "regex";
    regex: string;
}

function isRegexValidatorConfig(config: ValidatorConfig): config is RegexValidatorConfig {
    return config.type === "regex";
}

export function addRegexValidatorValidatorToFactory(factory: ValidatorFactory): void {
    factory.registerConstructor("regex", (config, params) => {
        if (!isRegexValidatorConfig(config)) return null;
        const regexValidatorParam: Partial<RegexValidator> = params as Partial<RegexValidator>;
        regexValidatorParam.regex = config.regex;

        return new RegexValidator(regexValidatorParam);
    });
}