var express = require("express");
const router = express.Router();
const db = require("../../utils/database");
const dbFuntion = require("../../utils/dbfunction");
const { response } = require("express");
const { sendEmail } = require("../../utils/Functions/DefectEmail");
const path = require("path");
const multer = require("multer");
const fs = require("fs");

const storage = multer.diskStorage({
  // https://www.npmjs.com/package/multer#diskstorage
  destination: "public/uploads",
  filename: function (req, file, cb) {
    cb(null, `image-${new Date().getTime()}.${file.mimetype.split("/")[1]}`);
  },
});
var upload = multer({ storage: storage });

router.get("/getImgagsMulter", (req, res) => {
  console.log("getImgagsMulter get Images req running ==>");
  const uploadDirectory = path.join("uploads");

  fs.readdir(uploadDirectory, (err, files) => {
    if (err) {
      return res.json({ message: err });
    }
    if (files.length === 0) {
      return res.json({ message: "No Images uploaded!" });
    }
    return res.json({
      files: files,
      message: "get image succussfully",
    });
  });
});

router.post("/uploadImage", upload.any("image"), (req, res, next) => {
  const url = req.protocol + "://" + req.get("host");
  console.log(url + "/uploads/" + req.files[0].filename);
  console.log("protocol", req.protocol);
  console.log("host", req.get("host"));
  console.log("post uploadImage Images req running ==>");

  // console.log("req body",req.body)
  // console.log("req files ===>",req.files)
  // console.log("uploaded file name: ", req.files[0].originalname);
  // console.log("file type: ", req.files[0].mimetype);
  // console.log("file name in server folders: ", req.files[0].filename);
  // console.log("file path in server folders: ", req.files[0].path);
  const image = url + "/uploads/" + req.files[0].filename;
  res.send({
    photo: image,
    // data: req.files,
    // data1: req.files[0].path,
    message: "Upload successfully",
  });
});

router.post("/createDefect", upload.any("image"), (req, res) => {
  // const url = req.protocol + "://" + req.get("host");
  const url = "https" + "://" + req.get("host");
  // console.log("body==>", req.body);
  console.log("files==>", req.files[0]);
  // if(req.files[0] === undefined || req.files[0] === null || req.files[0]=== " "){
  // }
  const department = req.body.department;
  const machine = req.body.machine;
  const equipmentName = req.body.equipmentName;
  // const line =req.body.line
  const hfound = req.body.hfound;
  const wfound = req.body.wfound;
  const priority = req.body.priority;
  const anamoly = req.body.anamoly;
  const defectStatus = req.body.defectStatus;
  const anamolyDetail = req.body.anamolyDetail;
  const responsible = req.body.responsible;
  const actionPlan = req.body.actionPlan;
  const targetDate = req.body.targetDate;
  const createdBy = req.body.createdBy;
  const createdOn = req.body.createdOn;
  const closeDate = req.body.closeDate;
  const solvedDate = req.body.solvedDate || "";
  const solvedBy = req.body.solvedBy || "";
  const defectPart = req.body.defectPart;
  const defectMonth = req.body.defectMonth;
  const repeatedDefect = req.body.repeatedDefect;

  console.log("defect ppart ", defectPart);
  if (
    req.files[0] === undefined ||
    req.files[0] === null ||
    req.files[0] === " "
  ) {
    var image = "No Image";
  } else {
    var image = url + "/uploads/" + req.files[0].filename;
  }
  // var image =  url + '/uploads/' + req.files[0].filename
  // console.log('imagee',image)
  const userId = req.body.userId;
  const defectYear = req.body.defectYear;
  // console.log('image',image)

  let EmailData = {
    department: department,
    machine: machine,
    owner: equipmentName,
    hfound: hfound,
    wfound: wfound,
    priority: priority,
    anamoly: anamoly,
    defectStatus: defectStatus,
    anamolyDetail: anamolyDetail,
    responsible: responsible,
    actionPlan: actionPlan,
    targetDate: targetDate,
    createdBy: createdBy,
    createdOn: createdOn,
    defectPart: defectPart,
    defectMonth: defectMonth,
    repeatedDefect: repeatedDefect,
    image: image,
  };

  if (
    department === "" ||
    machine === "" ||
    equipmentName === "" ||
    hfound === "" ||
    wfound === "" ||
    anamoly === "" ||
    defectStatus === "" ||
    responsible === "" ||
    actionPlan === ""
  ) {
    res.status(401).json({
      message: "Please fill all fields",
      results: "Failed",
    });
  } else {
    db.getConnection((err, connection) => {
      if (err) {
        console.log("database not connected error: >>>", err);
        throw err;
      }
      console.log("get Connection");
      var query = `insert into finehhdi_eDefect.defect (department,machine,equipmentName,hfound,wfound,priority,anamoly,defectStatus,anamolyDetail,responsible,actionPlan,targetDate,closeDate,createdOn,createdBy,repeatedDefect,defectMonth,defectPart,solvedDate,solvedBy,imageFile,userId,defectYear)
        values ("${department}","${machine}","${equipmentName}","${hfound}","${wfound}","${priority}","${anamoly}","${defectStatus}","${anamolyDetail}","${responsible}","${actionPlan}","${targetDate}","${closeDate}","${createdOn}","${createdBy}","${repeatedDefect}","${defectMonth}","${defectPart}","${solvedDate}","${solvedBy}","${image}",${userId},"${defectYear}");`;
      console.log("createQuery", query);

      connection.query(query, (err, result) => {
        connection.release();
        if (err) {
          console.log("error ==>", err);
          if (err.code === "ER_DUP_ENTRY") {
            res.status(409).json({
              message: "Duplicate User",
              results: "Failed",
            });
          } else if (err.code === "ENOTFOUND") {
            res.status(404).json({
              message: "Internet Connection Failed",
              results: "failed",
            });
          }
        } else {
          sendEmail(EmailData);
          // console.log(result)
          res.status(200).json({
            message: "defect Created Successfully",
            results: "Success",
          });
        }
      });

      console.log("release Connection");
    });
  }
});

module.exports = router;
