var express = require('express');
var router = express.Router();

var cheerio = require('cheerio');

var models = require('../models');
var Sequelize = require('sequelize');

var jsesc = require('jsesc');
var _ = require('lodash');

router.get('/', function(req, res, next) {
  res.render('index', {
    title: 'Welcome to ResourcePerf',
    testcase: {},
    documents: [{}, {}] // 2
  });
});

router.post('/', function(req, res, next) {
  var chainer = new Sequelize.Utils.QueryChainer;

  // Create test case
  var testCase = models.TestCase.build(req.body);
  chainer.add(testCase.save());

  // Create documents
  var documents = req.body.document.map((s) => models.Document.build(s));
  documents.forEach((s) => chainer.add(s.save()));

  chainer
    .run()
    .then(function () {
      // Associate documents w/ test case
      testCase.setDocuments(documents).then(function () {
        res.redirect('/' + req.body.slug);
      });
    });
});


router.get('/:slug', function (req, res, next) {
  models.TestCase.find({
    where: {slug: req.params.slug }
  }).then(function (testcase) {
    if (!testcase) {
      res.status(404);
      return res.render('404');
    }

    testcase.getDocuments().then(function (documents) {
      res.render('testcase/show', {
        title: testcase.name,
        testcase: testcase,
        documents: documents,
        documentJson: JSON.stringify(documents).replace(/\</g, '\\\\u005C')
      });
    });
  });
});

router.get('/:slug/edit', function (req, res, next) {
  models.TestCase.find({
    where: {slug: req.params.slug }
  }).then(function (testcase) {
    if (!testcase) {
      res.status(404);
      return res.render('404');
    }

    testcase.getDocuments().then(function (documents) {
      res.render('testcase/edit', {
        title: testcase.name,
        testcase: testcase,
        documents: documents
      });
    });
  });
});

router.post('/:slug/update', function (req, res, next) {
  var chainer = new Sequelize.Utils.QueryChainer;

  chainer.add(
    models.TestCase.update(_.pick(req.body, ['name', 'desc', 'slug']), {
      where: { id : req.body.id }
    })
  );

  req.body.document.forEach(function (doc) {
    chainer.add(models.Document.update(_.omit(doc, 'id'), {
      where: { id : doc.id }
    }));
  });

  chainer
    .run()
    .then(function () {
      res.redirect('/' + req.body.slug);
    });
});

router.get('/document/new', function (req, res, next) {
  res.render('partials/_document', {
    index: req.query.index
  });
});

function showDocument(req, res, next, cache) {
  models.Document.find(req.params.id).then(function (document) {
    // current time in microseconds
    var hrtime = process.hrtime();
    var cachebuster = hrtime[0] * 1000000 + hrtime[1] / 1000;

    var $ = cheerio.load(document.head);
    $('[src]').each(function () {
      $(this).attr('src', $(this).attr('src') + '?' + cachebuster);
    });
    var head = $.html();

    $ = cheerio.load(document.body);
    $('[src]').each(function () {
      $(this).attr('src', $(this).attr('src') + '?' + cachebuster);
    });
    var body = $.html();

    res.render('document', {
      document: document,
      head: head,
      body: body,
      layout: false
    });
  });
}

router.get('/document/:id/nocache', function (req, res, next) {
  models.Document.find(req.params.id).then(function (document) {
    // current time in microseconds
    var hrtime = process.hrtime();
    var cachebuster = hrtime[0] * 1000000 + hrtime[1] / 1000;

    var $ = cheerio.load(document.head);
    $('[src]').each(function () {
      $(this).attr('src', $(this).attr('src') + '?' + cachebuster);
    });
    var head = $.html();

    $ = cheerio.load(document.body);
    $('[src]').each(function () {
      $(this).attr('src', $(this).attr('src') + '?' + cachebuster);
    });
    var body = $.html();

    res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
    res.set('Pragma', 'no-cache');
    res.set('Expires', '0');


    res.render('document', {
      document: document,
      head: head,
      body: body,
      layout: false
    });
  });
});

router.get('/document/:id', function (req, res, next) {
  models.Document.find(req.params.id).then(function (document) {
    res.render('document', {
      document: document,
      head: document.head,
      body: document.body,
      layout: false
    });
  });
});


module.exports = router;

@@ -948,17 +948,16 @@
 );%0A%7D);%0A%0A
-%0A
 router.g
@@ -2523,732 +2523,8 @@
 );%0A%0A
-function showDocument(req, res, next, cache) %7B%0A  models.Document.find(req.params.id).then(function (document) %7B%0A    // current time in microseconds%0A    var hrtime = process.hrtime();%0A    var cachebuster = hrtime%5B0%5D * 1000000 + hrtime%5B1%5D / 1000;%0A%0A    var $ = cheerio.load(document.head);%0A    $('%5Bsrc%5D').each(function () %7B%0A      $(this).attr('src', $(this).attr('src') + '?' + cachebuster);%0A    %7D);%0A    var head = $.html();%0A%0A    $ = cheerio.load(document.body);%0A    $('%5Bsrc%5D').each(function () %7B%0A      $(this).attr('src', $(this).attr('src') + '?' + cachebuster);%0A    %7D);%0A    var body = $.html();%0A%0A    res.render('document', %7B%0A      document: document,%0A      head: head,%0A      body: body,%0A      layout: false%0A    %7D);%0A  %7D);%0A%7D%0A%0A
 rout
@@ -3666,17 +3666,16 @@
 );%0A%7D);%0A%0A
-%0A
 module.e
@@ -3690,9 +3690,8 @@
  router;
-%0A

Remove unused showDocument function