var express = require("express");
const router = express.Router();
const db = require("../../utils/database");

router.get("/getDefectParts", (req, res) => {
  db.getConnection((err, connection) => {
    if (err) {
      console.log("database not connected error: >>>", err);
      throw err;
    }
    console.log("get Connection");
    var query = `select * from finehhdi_eDefect.DefectParts order by id desc`;
    connection.query(query, (err, result) => {
      connection.release();
      if (err) {
        res.status(401).json({
          message: "Some error in type selection",
          results: "Failed",
          defectPart: [],
        });
      } else {
        res.status(201).json({
          message: "type Successfully",
          results: "Success",
          defectPart: result,
        });
      }
    });
    console.log("release Connection");
  });
});

router.post("/getDefectPartsFromMachine", (req, res) => {
  const machineType = req.body.machineType;

  db.getConnection((err, connection) => {
    if (err) {
      console.log("database not connected error: >>>", err);
      throw err;
    }
    console.log("get Connection");
    var query = `select * from finehhdi_eDefect.DefectParts where machineType= "${machineType}"`;
    connection.query(query, (err, result) => {
      connection.release();
      if (err) {
        res.status(401).json({
          message: "Some error in type selection",
          results: "Failed",
          defectPart: [],
        });
      } else {
        res.status(201).json({
          message: "type Successfully",
          results: "Success",
          defectPart: result,
        });
      }
    });
    console.log("release Connection");
  });
});

module.exports = router;
