import { reactive } from "@vue/reactivity";
import useValidators from './validators'


const errors = reactive({});
const errorMessage = reactive({});


export default function useFormValidation() {


    const { isEmpty, minLength, isEmail, isNum,isInt,maxLength } = useValidators();

    const validateNameField = (fieldName, fieldValue) => {
        errors[fieldName] = !fieldValue ? isEmpty(fieldName, fieldValue) : minLength(fieldName, fieldValue, 4)
    }

    const validateEmailField = (fieldName, fieldValue) => {
        errors[fieldName] = !fieldValue ? isEmpty(fieldName, fieldValue) : isEmail(fieldName, fieldValue)
    }

    const validatePhoneField = (fieldName, fieldValue) => {
        errors[fieldName] = !fieldValue ? isEmpty(fieldName, fieldValue) : isNum(fieldName, fieldValue)
    }

    const validatePasswordField = (fieldName, fieldValue) => {
        errors[fieldName] = !fieldValue ? isEmpty(fieldName, fieldValue) : minLength(fieldName, fieldValue, 8)
    }

    const validate = (rules,messages,fieldName, fieldValue) => {
        let container = {}
        container["required"] = isEmpty(fieldName,fieldValue)
        container["email"] = !fieldValue ? isEmpty(fieldName, fieldValue) : isEmail(fieldName, fieldValue)
        container["password"] = !fieldValue ? isEmpty(fieldName, fieldValue) : minLength(fieldName, fieldValue,6)
        container["integer"] = !fieldValue ? isEmpty(fieldName, fieldValue) : isInt(fieldName, fieldValue)

        for (let i in rules){
            errors[fieldName] = "";
            let value = rules[i];
            if(container[value]){
                errors[fieldName] = container[value];
                break;
            }else {

                let splited = value.split(':')
                if (splited.length == 2) {
                    container[value] = dyanamicValidation(splited, fieldValue, fieldName)
                    if(container[value]){
                        errors[fieldName] = container[value];
                        break;
                    }
                }

            }
        }

    }

    const dyanamicValidation = (splited,fieldValue,fieldName) => {
        let result = "";
        switch (splited[0]){
            case "min":
                result = !fieldValue ? isEmpty(fieldName, fieldValue) : minLength(fieldName, fieldValue,splited[1])
                break;
            case "max":
                result = !fieldValue ? isEmpty(fieldName, fieldValue) : maxLength(fieldName, fieldValue,splited[1])
                break;
            default:
                break
        }

        return result;
    }


    return { errors,validate}
}
