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

router.post("/createFeedbackNew", (req, res) => {
  const data = req.body.NewData;
  console.log("newData", req.body);
  Object.values(data).forEach((val) => {
    let query = `UPDATE finehhdi_CIL.FeedbackCIL1 set TaskDetail="${val.TaskDetail}",OperDesVal="${val.OperDesVal}"
    where id=${val.id}
    `;
    console.log("Update Feedback Query", query);
    db.getConnection((err, connection) => {
      if (err) {
        console.log("database not connected error: >>>", err);
        res.send(500).status({
          message: "Error from database",
          err: err,
        });
      }

      connection.query(query, (err, data) => {
        connection.release();
        if (err) {
          console.log("err", err);
        } else {
          res.status(200).send();
        }
      });
    });
  });
});

router.post("/insertDataIntoFeedback", (req, res) => {
  const data = req.body;
  const areaName = data.areaName;
  const machineName = data.machineName;
  const userId = data.userId;
  // const submittedOn = moment().format("DD-MM-YYYY");
  const submittedOn = data.submittedOn;
  // const now = new Date().toUTCString()
  // console.log("now ==>", now);
  db.getConnection((err, connection) => {
    if (err) {
      console.log("database not connected error: >>>", err);
      res.send(500).status({
        message: "Error from database",
        err: err,
      });
    }
    const selectQuery = `SELECT * FROM finehhdi_CIL.SETCIL1 WHERE areaName="${areaName}" and machineName="${machineName}"`;
    connection.query(selectQuery, (err, data) => {
      connection.release();
      // db.release();
      // db.end()

      if (err) {
        console.log(
          "error from selectQuery finehhdi_CIL.SETCIL1 insertDataIntoFeedback ==>",
          err
        );
      } else {
        // console.log(
        //   "data finehhdi_CIL.SETCIL1 insertDataIntoFeedback ===>",
        //   data
        // );
        if (data.length > 0) {
          // Due task work start =============================================================================================>
          // const selectFeedbackQuery = `SELECT * FROM finehhdi_CIL.FeedbackCIL1 WHERE areaName="${areaName}" and machineName="${machineName}"`;
          // const selectFeedbackQuery = `SELECT * FROM finehhdi_CIL.FeedbackCIL1 WHERE areaName="${areaName}" and machineName="${machineName}" ORDER BY id DESC `;
          const selectFeedbackQuery = `SELECT * FROM finehhdi_CIL.FeedbackCIL1 WHERE areaName="${areaName}" and machineName="${machineName}" ORDER BY submittedOn DESC `;
          db.getConnection((err, connection) => {
            if (err) {
              console.log("database not connected error: >>>", err);
              res.send(500).status({
                message: "Error from database",
                err: err,
              });
            }
            connection.query(selectFeedbackQuery, (err, selectFeedbackData) => {
              connection.release();
              // db.release();
              if (err) {
                console.log("error from selectFeedbackQuery ==>", err);
              } else {
                // console.log("result from selectFeedbackQuery ===>", selectFeedbackData);
                let submittedDatesArray = selectFeedbackData.map(
                  (item) => item.SubmittedOn
                );
                // console.log("last SubmittedOn Date ===>", submittedDatesArray);
                let lastSubmittedDate = submittedDatesArray
                  ? submittedDatesArray[0]
                  : moment().format("DD-MM-YYYY");
                console.log("lastSubmittedDate ==>", lastSubmittedDate);

                if (lastSubmittedDate) {
                  console.log(
                    "last Submitted Date found ===>",
                    lastSubmittedDate
                  );
                  // if last submitted Date and currunt date same then >
                  if (lastSubmittedDate == submittedOn) {
                    return res
                      .status(202)
                      .json({ message: "Task is Already Submitted" });
                    // res.writeHead(202, { "Content-Type": "application/json" });
                    // res.end(
                    //   JSON.stringify({
                    //     message: "Task is Already Submitted!",
                    //   })
                    // );
                    // return;
                  }

                  let datesArray1 = data.map((item) => {
                    let withOutSplitArr = item.startDay;
                    let withSplitArr = withOutSplitArr.split(",");
                    return {
                      operDesc: item.operDesc,
                      frequency: item.frequency,
                      dates: withSplitArr,
                    };
                  });
                  // console.log("datesArray1 ==>", datesArray1);

                  let sd = lastSubmittedDate;
                  // console.log("sd ==>", sd);
                  // let ed = moment().format("DD-MM-YYYY");
                  // let ed = "19-04-2022";
                  let ed = submittedOn;
                  console.log("ed ==>", ed);

                  let result3 = datesArray1.map((element) => {
                    // console.log("element ==>", element);
                    let re = element.dates.filter((d) => {
                      let day = d;
                      return (
                        moment(String(sd), "DD-MM-YYYY") <
                          moment(String(day), "DD-MM-YYYY") &&
                        moment(String(day), "DD-MM-YYYY") <=
                          moment(String(ed), "DD-MM-YYYY")
                      );
                    });
                    // return re;
                    return {
                      dates: re,
                      frequency: element.frequency,
                      operDesc: element.operDesc,
                    };
                  });
                  console.log("result3 ==>", result3);
                  result3.map((allDates, resultIndex) => {
                    console.log("result Index ===>", resultIndex);
                    console.log("allDates ===>", allDates);
                    const dates = allDates.dates;
                    // let duesDatesFilter = dates.filter((item) => item.length == 0);
                    // console.log("duesDatesFilter ===>", duesDatesFilter);
                    let duesDatesFilter = result3.filter((item) => {
                      return item.dates.length == 0;
                    });
                    console.log("duesDatesFilter ===>", duesDatesFilter);
                    // // // loop on data array ==========================================>
                    data.map((item, dataIndex) => {
                      console.log("data index ==>", dataIndex);
                      // // // loop on dates array =======================================>
                      dates.map((dueDate, dueDateIndex) => {
                        console.log("dueDate Index ====>", dueDateIndex);
                        console.log("dueDate ====>", dueDate);
                        if (duesDatesFilter.length >= 1) {
                          console.log("if block running ====>");
                          let duesFrequency = duesDatesFilter.map(
                            (freq) => freq.frequency
                          );
                          // console.log("duesFrequency ==>", String(duesFrequency));
                          console.log("duesFrequency ==>", duesFrequency);
                          var isFound = [];
                          // // //  loop on duesFrequency Array ===========================>
                          duesFrequency.forEach((duesFre, duesFreqIndex) => {
                            console.log("duesFreqIndex ====>", duesFreqIndex);
                            console.log("duesFre ====>", duesFre);
                            console.log(
                              "item.frequency ======>",
                              item.frequency
                            );
                            console.log(
                              "allDates.operDesc ======>",
                              allDates.operDesc
                            );
                            console.log("item.operDesc ======>", item.operDesc);
                            if (item.frequency === duesFre) {
                              console.log("This will not be inserted");
                            } else {
                              console.log("else block inserted ");
                              if (
                                item.frequency !== duesFre &&
                                item.operDesc === allDates.operDesc
                              ) {
                                console.log("This will be inserted ===>");
                                console.log("isFound ==============>", isFound);
                                if (isFound.length == 0) {
                                  console.log("only first time entry");
                                  console.log(
                                    "allDates.operDesc ======>",
                                    allDates.operDesc
                                  );
                                  console.log(
                                    "item.operDesc ======>",
                                    item.operDesc
                                  );
                                  isFound.push(1);
                                  db.getConnection((err, connection) => {
                                    if (err) {
                                      console.log(
                                        "database not connected error: >>>",
                                        err
                                      );
                                      res.send(500).status({
                                        message: "Error from database",
                                        err: err,
                                      });
                                    }
                                    const insertQuery = `INSERT INTO finehhdi_CIL.FeedbackCIL1 (userId,areaName, machineName,equipmentOwnerName, subAssemblyName,frequency,OperDes,OperDesVal,TaskDetail,submittedOn,OPL)
                                    values(${userId},"${item.areaName}", "${item.machineName}","${item.equipmentOwnerName}", "${item.subAssemblyName}","${item.frequency}","${item.operDesc}","", "","${dueDate}", "${item.OPL}")
                                    `;
                                    connection.query(
                                      insertQuery,
                                      (err, insertResult) => {
                                        connection.release();
                                        // db.release();
                                        if (err) {
                                          console.log(
                                            "error form inser FeedbackCIL1 ==>",
                                            err
                                          );
                                        } else {
                                          console.log("succesfull");
                                          res.status(200).send();
                                        }
                                      }
                                    );
                                  });
                                } else {
                                  console.log(
                                    "isFound in else block ===>",
                                    isFound
                                  );
                                  console.log(
                                    "allDates.operDesc ======>",
                                    allDates.operDesc
                                  );
                                  console.log(
                                    "item.operDesc ======>",
                                    item.operDesc
                                  );
                                }
                                // console.log(areaName);
                                // console.log(machineName);
                                // console.log(item.subAssemblyName);
                                // console.log(item.frequency);
                                // console.log(item.operDesc);
                                // console.log(dueDate);
                                // const selectFeedbackQuery = `SELECT * FROM finehhdi_CIL.FeedbackCIL1 WHERE userId=${userId} and areaName="${areaName}"
                                // and machineName="${machineName}"
                                // and subAssemblyName="${item.subAssemblyName}"
                                // and frequency="${item.frequency}"
                                // and OperDes="${item.operDesc}"
                                // and submittedOn="${dueDate}"
                                //  `;
                                // db.query( selectFeedbackQuery, (err, selectFeedbackResult) => {
                                //     // db.release();
                                //     if (err) {
                                //       console.log(  "error form select FeedbackCIL1 ==>",  err);
                                //     } else {
                                //       let feedbackResult = selectFeedbackResult
                                //       console.log(  "feedbackResult.length  ======>",  feedbackResult.length);
                                //       if (feedbackResult.length >= 1) {
                                //         console.log("Already submitted");
                                //       }
                                //       else{
                                //       // if(feedbackResult.length == 0){
                                //         console.log("Inserted =============>");
                                //         const insertQuery = `INSERT INTO finehhdi_CIL.FeedbackCIL1 (userId,areaName, machineName,equipmentOwnerName, subAssemblyName,frequency,OperDes,OperDesVal,TaskDetail,submittedOn,OPL)
                                //         values(${userId},"${item.areaName}", "${item.machineName}","${item.equipmentOwnerName}", "${item.subAssemblyName}","${item.frequency}","${item.operDesc}","", "","${dueDate}", "${item.OPL}")
                                //         `;
                                //         db.query( insertQuery, (err, insertResult) => {
                                //             // db.release();
                                //             if (err) {
                                //               console.log(  "error form inser FeedbackCIL1 ==>",  err);
                                //             } else {
                                //               console.log("succesfull");
                                //               res.status(200).send();
                                //             }
                                //           });
                                //       }
                                //     }
                                //   }
                                // );
                              }
                            }
                          });
                          isFound = [];
                        } else {
                          console.log("else block running =====>");
                          console.log("item.operDesc ===>", item.operDesc);
                          console.log(
                            "allDates.operDesc ===>",
                            allDates.operDesc
                          );
                          console.log("item.frequency ===>", item.frequency);
                          console.log(
                            "allDates.frequency ===>",
                            allDates.frequency
                          );
                          if (
                            item.frequency == allDates.frequency &&
                            item.operDesc == allDates.operDesc
                          ) {
                            console.log("condition true");
                            db.getConnection((err, connection) => {
                              if (err) {
                                console.log(
                                  "database not connected error: >>>",
                                  err
                                );
                                res.send(500).status({
                                  message: "Error from database",
                                  err: err,
                                });
                              }
                              const insertQuery = `INSERT INTO finehhdi_CIL.FeedbackCIL1 (userId,areaName, machineName,equipmentOwnerName, subAssemblyName,frequency,OperDes,OperDesVal,TaskDetail,submittedOn,OPL)
                              values(${userId},"${item.areaName}", "${item.machineName}","${item.equipmentOwnerName}", "${item.subAssemblyName}","${item.frequency}","${item.operDesc}","", "","${dueDate}", "${item.OPL}")
                              `;
                              // console.log("Create Feedback Query", insertQuery);

                              connection.query(
                                insertQuery,
                                (err, insertResult) => {
                                  connection.release();
                                  if (err) {
                                    console.log(
                                      "error form inser FeedbackCIL1 ==>",
                                      err
                                    );
                                  } else {
                                    console.log("Data Inserted Successfully");
                                    // res.status(200).send({message: "Data Inserted Successfully"});
                                    // res.status(200).send();
                                    res.send();
                                    // db.release()
                                    // db.end()
                                  }
                                }
                              );
                            });
                          }
                        }
                      });
                    });
                  });
                } else {
                  console.log(
                    "last submitted Date not found means this is first entry against this area and machine"
                  );
                  // console.log('data ==>', data);
                  data.map((item, itemIndex) => {
                    console.log("item Index ==>", itemIndex);
                    // console.log('item ==>', item);
                    // console.log('item ==>', item.startDay);
                    const datesArray = item.startDay;
                    const splitDatesArray = datesArray.split(",");
                    // console.log("splitDatesArray ===>", splitDatesArray);
                    const isDate = splitDatesArray.filter(
                      (fil) => fil == submittedOn
                    );
                    console.log("isDate ==============>", isDate);
                    if (isDate.length > 0) {
                      console.log("isDate Found");
                      db.getConnection((err, connection) => {
                        if (err) {
                          console.log("database not connected error: >>>", err);
                          res.send(500).status({
                            message: "Error from database",
                            err: err,
                          });
                        }
                        const selectFeedback = `SELECT * FROM finehhdi_CIL.FeedbackCIL1 where areaName="${areaName}" AND machineName="${machineName}" AND userId=${userId} AND SubmittedOn="${submittedOn}"`;
                        console.log(
                          "selectFeedback ==========>",
                          selectFeedback
                        );
                        connection.query(selectFeedback, (err, response) => {
                          connection.release();

                          if (err) {
                            console.log(
                              "err from select FeedbackCIL1 ===?>",
                              err
                            );
                          } else {
                            console.log(
                              "response from FeecbackCIL1 ==>",
                              response
                            );
                            if (response.length > 0) {
                              console.log("response.length is greater then 0");
                              // console.log("already exist");
                              // res.status(301).send({message: "Already Exist"});
                              // res.status(202).send();
                              response.map((res, resIndex) => {
                                if (
                                  res.areaName == item.areaName &&
                                  res.machineName == item.machineName &&
                                  res.subAssemblyName == item.subAssemblyName &&
                                  res.frequency == item.frequency &&
                                  res.operDesc == item.operDesc &&
                                  res.submittedOn == item.submittedOn
                                ) {
                                  console.log("already exist");
                                  // // // new approach
                                  // res.writeHead(202, { 'Content-Type': 'application/json' });
                                  // res.end(JSON.stringify({
                                  //   message: 'Task is Already Exist!'
                                  // }));
                                } else {
                                  console.log("not exist in response.map");
                                  db.getConnection((err, connection) => {
                                    if (err) {
                                      console.log(
                                        "database not connected error: >>>",
                                        err
                                      );
                                      res.send(500).status({
                                        message: "Error from database",
                                        err: err,
                                      });
                                    }
                                    const insertQuery = `INSERT INTO finehhdi_CIL.FeedbackCIL1 (userId,areaName, machineName,equipmentOwnerName, subAssemblyName,frequency,OperDes,OperDesVal,TaskDetail,submittedOn,OPL)
                                      values(${userId},"${item.areaName}", "${item.machineName}","${item.equipmentOwnerName}", "${item.subAssemblyName}","${item.frequency}","${item.operDesc}","", "","${submittedOn}", "${item.OPL}")
                                      `;
                                    console.log(
                                      "Create Feedback Query",
                                      insertQuery
                                    );

                                    connection.query(
                                      insertQuery,
                                      (err, insertResult) => {
                                        connection.release();

                                        if (err) {
                                          console.log(
                                            "error form inser FeedbackCIL1 ==>",
                                            err
                                          );
                                        } else {
                                          console.log("succesfull =>");
                                          // res.status(200).send({message: "Data Inserted Successfully"});
                                          // res.status(200).send();
                                          // res.sendStatus(200);
                                          // // // new approach
                                          // res.writeHead(200, { 'Content-Type': 'application/json' });
                                          // res.end(JSON.stringify({
                                          //   message: 'Inserted Successfully!'
                                          // }));
                                          res.send();
                                        }
                                      }
                                    );
                                  });
                                  // db.release();
                                  // db.end()
                                }
                              });
                            } else {
                              console.log("not exist");
                              // res.status(200).send();
                              db.getConnection((err, connection) => {
                                if (err) {
                                  console.log(
                                    "database not connected error: >>>",
                                    err
                                  );
                                  res.send(500).status({
                                    message: "Error from database",
                                    err: err,
                                  });
                                }
                                const insertQuery = `INSERT INTO finehhdi_CIL.FeedbackCIL1 (userId,areaName, machineName,equipmentOwnerName, subAssemblyName,frequency,OperDes,OperDesVal,TaskDetail,submittedOn,OPL)
                                values(${userId},"${item.areaName}", "${item.machineName}","${item.equipmentOwnerName}", "${item.subAssemblyName}","${item.frequency}","${item.operDesc}","", "","${submittedOn}", "${item.OPL}")
                                `;
                                console.log(
                                  "Create Feedback Query",
                                  insertQuery
                                );

                                connection.query(
                                  insertQuery,
                                  (err, insertResult) => {
                                    connection.release();

                                    if (err) {
                                      console.log(
                                        "error form inser FeedbackCIL1 ==>",
                                        err
                                      );
                                    } else {
                                      console.log("succesfull");
                                      // res.status(200).send({message: "Data Inserted Successfully"});
                                      // res.status(200).send();
                                      // res.sendStatus(200);

                                      // // // new approach
                                      // res.writeHead(200, { 'Content-Type': 'application/json' });
                                      // res.end(JSON.stringify({
                                      //   message: 'Inserted Successfully!'
                                      // }));
                                    }
                                  }
                                );
                              });

                              // db.release();
                              // db.end()
                            }
                          }
                        });
                      });
                      // db.release();
                      // db.end()
                    } else {
                      // res.status(204).writeHead().send()
                      // res.sendStatus(204);
                      // res.status(204).send();
                      // res.statusCode = 204;
                      // res.sendStatus(204);
                      console.log("date not matched");
                      // // // new approach
                      // res.writeHead(204, { 'Content-Type': 'application/json' });
                      // res.end(JSON.stringify({
                      //   message: 'date not matched!'
                      // }));
                    }
                  });
                }
              }
            });
          });
        } else {
          res.status(204).send({
            message: "Task is not assigned",
          });
          // db.end()
        }
      }
    });
  });
});
module.exports = router;
