const express = require("express")
const bodyParser = require("body-parser");
const app = express();
const hbs = require('hbs');
const path = require('path');
const db = require("./db")
const session = require("express-session");
require("./moderator");
hbs.registerPartials(path.join(__dirname, 'views/partials'));

app.use(session({
  secret: 'this is the most random keyphrase  that you have ever encountered. it should be very secure and not easy to crack so that nobody can fake the cookie',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false, httpOnly: false }
}))

app.use(bodyParser.urlencoded());

app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));

function addErrors(request) {
   return []
}

function checkForm(fields, data) {
   for (let field in fields) {
      if (!(data.hasOwnProperty(field) && typeof data[field] === fields[field])) {
         return false;
      }
   }

   return true;
}

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

app.get("/login", (req, res) => {
   const errors = addErrors(req)
   res.render("login",{
      errors,
   })
});

app.post("/login", (req, res) => {
   if (!checkForm({
      username: "string",
      password: "string",
   }, req.body)) {
      res.redirect("/login?error=invalid")
   } else {
      const user = db.checkLogin(req.body.username, req.body.password);
      if (user) {
         req.session.loggedIn = user;
         res.redirect("/posts")
      } else {
         res.redirect("/login?error=invalid pwd")
      }
   }
});

app.post("/register", (req, res) => {
   if (!checkForm({
      username: "string",
      password: "string"
   }, req.body)) {
      res.redirect("/register?error")
   } else {
      const registerTry = db.registerUser(req.body.username, req.body.password); 
      if (registerTry) {
         res.redirect("/register?error=user already exists");
      } else {
         res.redirect("/login")
      }
   }
});


app.get("/register", (req, res) => {
   const errors = addErrors(req)
   res.render("register", {
      errors,
   })
});

app.get("/posts", (req, res) => {
   if (req.session.loggedIn) {
      const userId = req.session.loggedIn;
      const posts  = db.getPostsBy(userId); 
      res.render("posts", {posts: posts});
   } else {
      res.redirect("/login");
   }
});

app.get("/create", (req, res) => {
   if (req.session.loggedIn) {
      res.render("create_post");
   } else {
      res.redirect("/login");
   }
});

app.post("/create", (req, res) => {
   if (req.session.loggedIn && !db.isModerator(req.session.loggedIn)) {
      if (checkForm({content: "string"}, req.body))  {
         const userId = req.session.loggedIn;
         db.addPost(req.body.content, userId);
         res.redirect("/posts")
      } else {
         res.redirect("/create");
      }
   } else {
      res.redirect("/login");
   }
});

app.get("/post/:id", (req, res) => {
   if (req.session.loggedIn) {
      const userId = req.session.loggedIn;
      const postId = req.params.id;
      const post = db.getPostById(postId);
      if (post.by !=  userId && !db.isModerator(userId)) {
         res.redirect("/posts");
      } else {
         res.render("post", {post: post});
      }
   } else {
      res.redirect("/login");
   }
});

app.get("/moderate", (req, res) => {
   if (db.isModerator(req.session.loggedIn)) {
      res.render("posts", {posts: db.getAllPosts() })
   } else {
      res.redirect("/posts?error=access denied");
   }
});

app.use(express.static('public'))
db.resetStore()

setInterval(() => { console.log("resetting store"); db.resetStore() }, 60*1000*15);

app.listen(8001);
