const fs = require('fs');
import {GoodsAttributes} from "../../models/index";


module.exports = (req, res, next) => {
    const {pictureName, goodsAttributesId} = req.body.decryptedData;


        if(goodsAttributesId) {
            GoodsAttributes.findOne({
                where: {
                    id: goodsAttributesId
                }
            }).then(elem => {
                const {imgUrlArray, goodsId} = elem;

                req.body.goodId = goodsId;


                if(imgUrlArray.indexOf(pictureName) != -1) {
                    imgUrlArray.splice(imgUrlArray.indexOf(pictureName), 1);

                    elem.update({
                        imgUrlArray: imgUrlArray
                    }).then(() => {
                        fs.unlink(`./public/photoGoods/${pictureName}`, (err) => {
                            if (err) {
                                next(err)
                            } else {
                                next();
                            }
                        })
                    })
                }else {
                    next();
                }
            });
        }else {
            if(Array.isArray(pictureName)) {
                pictureName.forEach(elem => {
                    fs.unlink(`./public/photoGoods/${elem}`, (err) => {
                        if (err) {
                            next(err)
                        } else {
                            next();
                        }
                    })
                });
            }else {
                next();
            }
        }

};