import { ValidationChain, ValidationEventArgs } from "../chainOfResponsibility";
import { EnumValidateState } from "../enums";
import { ElementFactory } from "../Page/ElementsOfFormFactory/ElementFactory";
import { IMainStateFactory } from "../Types";
import { Cach } from "./Cach";

export class PasswordBoxFactory extends ElementFactory {
    public forceUpdate = () => { };

    public value: string | null = null;
    public setValue = (value: string) => {
        this.value = value;
        Cach.setValue(this, value);

        this.forceUpdate();
    }

    public clearData: () => void = () => {
        Cach.clear(this);

    }
    public deseriallize: () => void = () => {

    }
    public refreshHasChange: () => void = () => {

    }
    public restartDefaultValue: () => void = () => {

    }

    constructor(
        mainStateFactory: IMainStateFactory,
        fieldName: string,
        _dispose: () => void,
        public caption: string,
        public placeHolder?: string,
        public tabIndex?: number,
        payLoadKey?: string,
        responseKey?: string,
    ) {
        super(mainStateFactory, fieldName, _dispose, payLoadKey, responseKey);


        if (Cach.isCached(this)) {
            const cach = Cach.getCached(this);
            this.value = cach.value;
            this.validation = cach.validation;
            this._hasChange = cach.hasChange;
        }
    }

    public validate = () => {
        var validationChain = new ValidationChain();

        validationChain.validators.add(this.validateRequired);

        this.validation = validationChain.validate();
    }
    private validateRequired = (eventArgs: ValidationEventArgs) => {
        if (!this.value) {
            eventArgs.error = 'پسورد وارد نشده است';
            eventArgs.state = EnumValidateState.empty;
            eventArgs.cancel = true;
        }
    };
}