const {
    body,
    validationResult
} = require('express-validator');
const validateCategory = () => {
    return [
        body('name', 'This field is required!').trim().notEmpty()
        .matches(/^[A-Za-z .,^()'_!?><";:`~&@#$%/*|-]+$/)
        .withMessage('Name must be alphabetic.'),
        body('base_image', 'This field is required!').notEmpty(),

    ];
}
const validateCat = (req, res, next) => {
    const errors = validationResult(req)
    
    var extractedErrors = [], errorFound = false;
    errors.array({ onlyFirstError: true }).map(err => extractedErrors.push({ [err.param]: err.msg }));

    var base_imageErr = {}, base_image_NewErr = {};
    var { base_image_other,base_image_new, } = req.body;
    if(base_image_other){
        if(base_image_other.length > 0){
            base_image_other.forEach((itm, i) => {
                if (itm == "") {
                    base_imageErr[i] = 'This field is required!';
                    errorFound = true;
                }
            })
        }else{
            if (base_image_other == "") {
                base_imageErr = 'This field is required!';
                errorFound = true;
            }
        }
    }
    if(base_image_new){
        if(base_image_new.length > 0){
            base_image_new.forEach((itm, i) => {
                if (itm == "") {
                    base_image_NewErr[i] = 'This field is required!';
                    errorFound = true;
                }
            })
        }else{
            if (base_image_new == "") {
                base_image_NewErr = 'This field is required!';
                errorFound = true;
            }
        }
    }
    if (Object.keys(base_imageErr).length > 0) {
        extractedErrors.push({ base_imageErr })
    }
    if (Object.keys(base_image_NewErr).length > 0) {
        extractedErrors.push({ base_image_NewErr })
    }
    if (errors.isEmpty() && !errorFound) {
        return next()
    }
    console.log("extractedErrors=>>>>>>>>>>>>>>>>>", extractedErrors)
    req.flash('validationError', extractedErrors);
    req.flash('form', req.body);
    if (req.params.id) {
        return res.redirect('/admin/category/' + req.params.id)
    }
    return res.redirect('/admin/category')
}
module.exports = {
    validateCategory,
    validateCat
}