
const express = require('express'),
    router = express.Router(),
    Document = require("../src/sequelize.js").Document,
    DocumentCover = require("../src/sequelize.js").DocumentCover,
    DocumentFile = require("../src/document.js").Document,
    templateArgs = require('../src/templateArgs.js');

function getDocumentInFormat(docId, format) {
    return new Promise((res, rej) => {
        Document.findOne({ attributes: [ "path" ], where: { id: docId }}).then(path => {
            if (!path) {
                rej(404);
                return;
            }
            const document = new DocumentFile(path.path);
            var doc = document.convert(format);
            doc.ready.then(content => {
                if (!content) {
                    doc.clean();
                    rej(500);
                    return;
                }
                res({ error: null, content: content });
                doc.clean();
            });
        });
    });
}

router.get('/:bookId/info.json', (req, res) => {
    Document.findOne({where: { id: req.params.bookId }}).then(doc => {
        if (!doc) {
            res.status(404);
            res.send("Book bot found");
            return;
        }
        res.set({ "Content-Type": "application/json" });
        res.send(JSON.stringify({
            title: doc.title,
            author: doc.author,
            identifier: doc.identifier,
            pageCount: doc.pageCount
        }));
    });
});

router.get('/:bookId/download.pdf', (req, res) => {
  templateArgs.needLogin(req, res).then(async () => {
      getDocumentInFormat(req.params.bookId, "pdf").then(doc => {
          res.set({
            "Content-Type": "application/pdf",
          });
          doc.content.pipe(res);
      }).catch(e => {
          res.status(e)
          res.send("Error");
      });
  });
});

router.get('/:bookId/download.epub', (req, res) => {
  templateArgs.needLogin(req, res).then(async () => {
      getDocumentInFormat(req.params.bookId, "epub").then(doc => {
          res.set({
            "Content-Type": "application/epub",
          });
          doc.content.pipe(res);
      }).catch(e => {
          res.status(e)
          res.send("Error");
      });
  });
});

router.get('/:bookId/cover.png', (req, res) => {
  templateArgs.needLogin(req, res).then(async () => {
    var cover = await DocumentCover.findOne({ where: {id: req.params.bookId }});
    if (!cover) {
      res.status(404);
      res.send("Not Found");
    } else {
      res.set({
        "Content-Type": "image/png",
      });
      res.send(cover.cover);
    }
  });
});

router.get('/:bookId/read/:pageNo.png', (req, res) => {
  templateArgs.needLogin(req, res).then(async () => {
    var path = await Document.findOne({ attributes: [ "path" ], where: { id: req.params.bookId }}),
        pageReq = parseInt(req.params.pageNo, 10);
    if (!path || pageReq <= 0) {
        res.status(404);
        res.send("Not Found");
        return;
    }
    const document = new DocumentFile(path.path),
          pageCount = document.getPageCount();
    if (pageReq > pageCount) {
        res.status(404);
        res.send("Not Found");
        return;
    }
    const content = await document.getPage(pageReq);
    if (content) {
      res.set({
        "Content-Type": "image/png",
      });
      res.send(content);
    } else {
      res.status(500);
      res.end("Error");
    }
  });
});

module.exports = router;
