const express = require("express");
const multer = require("multer");
const ejs = require("ejs");
const path = require("path");

const storage = multer.diskStorage({
  destination: "./public/uploads/",
  filename: function(req, file, callback) {
    callback(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 1000000 },
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  }
}).single("myImage");

function checkFileType(file, cb) {
  const filetypes = /jpeg|jpg|png|svg/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error(`Только изображения формата - png, jpg, jpeg`));
  }
}

const app = express();
const port = 3000 || process.env.PATH;

app.set("view engine", "ejs");

app.use(express.static("./public"));

app.get("/", (req, res) => {
  res.render("index");
});

app.post("/upload", (req, res) => {
  upload(req, res, err => {
    if (err) {
      res.render("index", { msg: err.message });
    } else {
      if (req.file == undefined) {
        res.render("index", { msg: "Пожалуйста, выберите файл для загрузки" });
      } else {
        res.render("index", {
          msg: "Файл обновлён!",
          file: `uploads/${req.file.filename}`
        });
      }
    }
  });
});

app.listen(port, () => {
  console.log(`Старт сайта ${port}`);
});
