import { Product, sequelize } from './model';
import formidable from 'formidable';
var randomize = require('randomatic');
import rimraf from 'fs-extra';
import { csrf } from 'src/lib/csrf';
const path = require('path');
const fs = require('fs');

async function update(req) {
  try {
    const form = formidable({});

    await sequelize.authenticate();
    let fields;
    let files;
    [fields, files] = await form.parse(req);

    let dir_prefix;

    let name = fields['name'][0];
    let description = fields['description'][0];
    let cid = fields['cid'][0];
    let pid = fields['pid'][0];
    let price = fields['price'][0];
    let clear_image = fields['clear_image'][0];

    let category;

    console.log('have file ?');
    const haveImage = files => {
      return files?.product_image?.length > 0;
    };
    console.log(haveImage(files));

    if (haveImage(files)) {
      dir_prefix = randomize('A', 5);

      let product_image = files['product_image'];

      for (var i = 0; i < files.product_image.length; i++) {
        product_image = files.product_image[i];
        let dest_path = path.join('./tmp', dir_prefix) + path.sep;

        try {
          rimraf.removeSync(dest_path);
        } catch (error) {
          console.error('error during removing directory, ignoring');
        }

        fs.mkdirSync(dest_path, { recursive: true });
        let bs = fs.readFileSync(product_image.filepath);
        fs.writeFileSync(dest_path + 'image.jpg', bs);
      }
    }

    if (haveImage(files)) {
      category = await Product.update(
        { name, description, cid: cid, price, product_image: dir_prefix },
        { where: { pid } },
      );
    } else {
      if (clear_image == 'true') {
        category = await Product.update({ name, description, cid: cid, price, product_image: '' }, { where: { pid } });
      } else {
        category = await Product.update({ name, description, cid: cid, price }, { where: { pid } });
      }
    }

    return { status: 'OK', category };
  } catch (error) {
    console.error(error);
  }
}

async function handler(req, res) {
  try {
    let result = await update(req);

    return res.status(200).send(result);
  } catch (err) {
    console.log(err);
    res.status(200).send({ status: 'error', message: 'update error' });
  }
}

export const config = {
  api: {
    bodyParser: false,
  },
};

export default csrf(handler);
