var express = require('express');
var net     = require('net');
var crypto  = require('crypto');

var router = express.Router();

var jsonsrv = require('../lib/jsonsrv');
var pcalutils = require('../lib/pcalutils');

router.get('/:taskuuid', function(req, res, next) {
	var jsondata = {
		"request"		: "init_task",
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {

			var date =  (new Date(Date.now())).toISOString().slice(0,10);

			if(result.result === "OK") {
				res.render('pcalpub', { date: date, publicationformats: result.publicationformats, sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "pcalpub"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/pcalpub/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/:taskuuid/download/:file', function(req, res, next) {
	var jsondata = {
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid,
		"request"		: "get_file",
		"filename"		: req.params.file
	};

	/*switch(req.params.file) {
		case "cards.pdf": jsondata.request = "get_cards"; break;
		case "envelopes.pdf": jsondata.request = "get_envelopes"; break;
		default:
			var err = new Error('Not Found');
			err.status = 404;
			res.render('error', {
				message: err.message,
				error: err
			});
			return;
	}*/

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK") {
				if(req.params.file.endsWith(".html"))
					res.setHeader("Content-Type", "text/html");
				else
					res.setHeader("Content-Type", "application/pdf");
				res.send(new Buffer(result.data, 'base64'));
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

module.exports = router;
