var express = require('express');
var router = express.Router();
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var push = require("./../push/push");
// var firebase = require('firebase');

//Database
var postgres = require("./../db-connect/db-connect");


var admin = require('firebase-admin');
var serviceAccount = require('../login/firebaseAdminKey.json');
var firebaseAdmin = admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://test-667ca.firebaseio.com'
  });

//Push
router.get('/push/:msgtoken/:message/:title', function (req, res, next) {
  
  push.sendPush(req.params.msgtoken, req.params.title, req.params.message);
  var sender = "Message Token: " + req.params.msgtoken + " Message: " + req.params.message + " Title: " + req.params.title;
  res.status(200).send(sender);
});


// Login und Dash
router.get('/', function (req, res, next) {
  res.render('index');
});


router.get('/dash/:idtoken', function (req, res, next) {
  // const msgtoken = req.params.msgtoken;
  const token = req.params.idtoken;
  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(function (decodedToken) {
      uid = decodedToken.uid;
      // HIER WEITER MACHEN
      // uid ist nur hier drinen verfügbar


    }).catch(function (error) {
      console.log(error)
    });




  res.render('dash');
});


router.get('/register', (req, res) => {
  res.status(200).render('registrieremail');
});


// SmartShopper

//GET Own shoppinglists as JSON

router.get("/myshoppinglists", async function (req, res, next) {
  var token = req.query.idtoken;
  console.log("/myshoppinglists idtoken: ", token)
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      console.log("uid", uid)
      try {
        //Get user id: req.session.passport.user.profile.id
        res.status(200).send(await postgres.getShoppinglistsAdmin(uid));
      } catch (err) {
        res.status(400).send(await err);
      }

    }).catch(function (error) {
      console.log(error)
    });


});

//Test Funktion für Android, liefert die FirebaseAdmin Skd UID 
// router.get("/androidUIDTest/:idtoken", function (req, res, next) {
//   var token = req.params.idtoken;
//   console.log("/sharedshoppinglists idtoken: ", token)
//   var uid;
//   firebaseAdmin.auth().verifyIdToken(token)
//     .then(async function(decodedToken) {
//       uid = decodedToken.uid;
//       console.log("UID: ", uid);
//         res.status(200).send(uid);

//   }).catch( async function(error) {
//    console.log(error)
//   });
// })

//GET Shared shoppinglists as JSON

router.get("/sharedshoppinglists", async function (req, res, next) {
  var token = req.query.idtoken;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      console.log("uid", uid)
      try {
        //Get user id: req.session.passport.user.profile.id
        res.status(200).send(await postgres.getShoppinglistsShared(uid));
      } catch (err) {
        res.status(400).send(await err);
      }

    }).catch(function (error) {
      console.log(error)
    });


});

//GET ALL SHOPPINGLISTS

router.get("/shoppinglistsbylink", async function (req, res, next) {
  var token = req.query.idtoken;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      console.log("uid", uid)
      try {
        //Get user id: req.session.passport.user.profile.id
        res.status(200).send(await postgres.getShoppinglistsByLink(req.query.link));
      } catch (err) {
        res.status(400).send(await err);
      }

    }).catch(function (error) {
      console.log(error)
    });


});

//POST new shoppinglist

router.post("/shoppinglist", async function (req, res, next) {
  console.log("/shoppinglist idtoken: ", req.body.idtoken)
  var token = req.body.idtoken;

  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      console.log("UID: ", uid);
      console.log("So andere sachen: ", req.body.name, req.body.description);
      try {

        res.status(200).send(await postgres.newShoppinglist(req.body.name, req.body.description, uid, req.body.color));
        sendPush("enG4tJ6LyyU:APA91bEYjUEs7Sdzvu2ivgfqtpzlg42BZLlujDSRg0WLBvfZ_oD4V7cTx2o6MVr4oAdeHaK0wttPMQ85GMMOkgM7xvbHFcwXUG4MCr8JXX16S-OV2CS4ikQ286DOHPtBotbM7pqFTvIM", "Einkaufsliste " + req.body.name + " wurde erstellt!", req.body.description)
      } catch (err) {
        res.status(400).send(await err);
      }
    }).catch(function (error) {
      console.log(error)
    });
});
//GET Shoppinglist detail

router.get("/shoppinglist_json/:sl_id", async (req, res) => {

  try {
    res.status(200).send(await postgres.displayShoppinglist(req.params.sl_id));
  } catch (err) {
    res.status(400).send(await err);
  }


});



postgres.displayShoppinglist("4tezJYMK");

//DELETE Shoppinglist

router.delete("/shoppinglist", async (req, res) => {

    var token = req.body.idtoken;
    var uid;
    firebaseAdmin.auth().verifyIdToken(token)
      .then(async function (decodedToken) {
        uid = decodedToken.uid;
  
        try {
          res.status(200).send(await postgres.deleteShoppinglist(req.body.sl_id, uid));
        } catch (err) {
          res.status(400).send(await err);
        }
      }).catch(function (error) {
        console.log(error)
      });
});

router.post("/movedoneitem", (req, res) => {
  var token = req.body.idtoken;
  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;

      try {
        res.status(200).send(await postgres.moveDoneItemMan(uid, req.body.sl_id, req.body.group_id, req.body.item_id));
      } catch (err) {
        res.status(400).send(await err);
      }
    }).catch(function (error) {
      console.log(error)
    });
});

//Group erstellen

router.post("/group", async (req, res) => {
  try {
    res.status(200).send(await postgres.addGroup(req.body.sl_id, req.body.name, req.body.color, req.body.hidden));
  } catch (err) {
    res.status(400).send(await err);
  }

});

//Item erstellen

router.post("/item", async (req, res) => {
  try {
    res.status(200).send(await postgres.addItem(req.body.group_id, req.body.sl_id, req.body.name, req.body.count));
  } catch (err) {
    res.status(400).send(await err);
  }
});

router.get("/test1", (req, res) => {
  res.render("test");
});

router.get("/userinfo_json", (req, res) => {
  var token = req.query.idtoken;

  console.log("/userinfo_json idtoken: ", token)
  firebaseAdmin.auth().verifyIdToken(token)
    .then(function (decodedToken) {
      res.send(decodedToken);
    }).catch(function (error) {
      console.log(error)
    });
});

//Rename Shoppinglist
router.put("/shoppinglist", async (req, res) => {
  try {
    res.status(200).send(await postgres.editShoppinglist(req.body.sl_id, req.body.name, req.body.description, req.body.color));
  } catch (err) {
    res.status(400).send(await err);
  }
});

//Rename Group

router.put("/group", async (req, res) => {
  try {
    res.status(200).send(await postgres.editGroup(req.body.sl_id, req.body.group_id, req.body.name, req.body.color, req.body.hidden));
  } catch (err) {
    res.status(400).send(await err);
  }
});

router.put("/item", async (req, res) => {
  try {
    res.status(200).send(await postgres.editItem(req.body.sl_id, req.body.group_id, req.body.item_id, req.body.name, req.body.count));
  } catch (err) {
    res.status(400).send(await err);
  }
});

router.delete("/group", async (req, res) => {
  try {
    res.status(200).send(await postgres.deleteGroup(req.body.group_id, req.body.sl_id));
  } catch (err) {
    res.status(400).send(await err);
  }
});

router.delete("/item", async (req, res) => {
  try {
    res.status(200).send(await postgres.deleteItem(req.body.item_id, req.body.group_id, req.body.sl_id));
  } catch (err) {
    res.status(400).send(await err);
  }
});

// Invite System

router.post("/invite", async (req, res) => {
  try {
    res.status(200).send(await postgres.createInvite(req.body.sl_id));
  } catch (err) {
    res.status(400).send(await err);
  }
});

router.post("/maninvite", async (req, res) => {
  try {
    res.status(200).send(await postgres.manInvite(req.body.sl_id, req.body.uid));
  } catch (err) {
    res.status(400).send(err);
  }


});

router.delete("/member", (req, res) => {
  try {
    postgres.removeMember(req.body.uid, req.body.sl_id)
  } catch (err) {
    return err;
  }
});

router.get("/invite/:invitelink", async (req, res) => {
  res.status(200).render("invite");
});

router.post("/invitemember", (req, res) => {

  var token = req.body.idtoken;
  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;

      try {
        console.log("Route LInk inv", req.body.link);
        res.status(200).send(await postgres.verifyInvite(req.body.link, uid));
      } catch (err) {
        res.status(400).send(await err);
      }
    }).catch(function (error) {
      console.log(error)
    });
});

//Update User

router.post("/user", async function (req, res, next) {
  console.log("/shoppinglist idtoken: ", req.body.idtoken)
  var token = req.body.idtoken;

  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      console.log("UID: ", uid);
      console.log("So andere sachen: ", req.body.name, req.body.description);
      try {

        res.status(200).send(await postgres.updateUser(uid, req.body.message_id, decodedToken.name, decodedToken.picture, decodedToken.email));
      } catch (err) {
        res.status(400).send(await err);
      }
    }).catch(function (error) {
      console.log(error)
    });
});

router.get("/users", async (req, res) => {
  try {
    res.status(200).send(await postgres.searchUsers(req.query.search));
  } catch (err) {
    res.status(400).send(err);
  }

});


//postgres.updateUser("testuser2", "einemessageid");


//postgres.moveDoneItems('dXMuv1J0f4O7RKn2bizGMTHUYkg1', '2IY2BwLP', 'aAnNNanas bjdbafBROtcHiPs');

router.post("/donepurchases", (req, res) => {
  var token = req.query.idtoken;
  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      try {
        console.log("test");
      } catch (err) {
        console.error(error);
      }
    }).catch(async function (error) {
      console.log(error)
    });

});


//GET Done Purchases
router.get("/donepurchases", (req, res) => {
  var token = req.query.idtoken;
  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      try {
        res.status(200).send(await postgres.getDonePurchases(uid));
      } catch (err) {
        res.status(400).send(await err);
      }
    }).catch(async function (error) {
      console.log(error)
    });

});


//OCR Scan


router.get("/scan/", async (req, res, ) => {
  res.render("ocrscan");
});


router.post("/dones", async function (req, res, next) {
  console.log("/shoppinglist idtoken: ", req.body.idtoken)
  var token = req.body.idtoken;

  var uid;
  firebaseAdmin.auth().verifyIdToken(token)
    .then(async function (decodedToken) {
      uid = decodedToken.uid;
      console.log("UID: ", uid);
      console.log("So andere sachen: ", req.body.name, req.body.description);
      try {

        res.status(200).send(await postgres.moveDoneItems(uid, req.body.sl_id, req.body.billcontent));
      } catch (err) {
        res.status(400).send(await err);
      }
    }).catch(function (error) {
      console.log(error)
    });
});

router.get("/dash2", (req, res) => {
  res.status(200).render("dash2");
});



module.exports = router;