summaryrefslogtreecommitdiff
path: root/modules/datumpjeprik/datumpjeprik.js
blob: c0c9c3d7b2b2de910cfda3f42cf39236ae66c992 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var cmn=require("../$common.js");
var persist=require("node-persist"),
    util=require("util");

//Sorry. Prototypes are fun. Using dollars to at least separate these from the built-in methods.
Date.prototype.$dayOfWeek=function(){return (this.getDay()+6)%7;} //monday..sunday = 0..6
Date.prototype.$startOfDay=function(){return new Date(this-(((this.getHours()*60+this.getMinutes())*60+this.getSeconds())*1000+this.getMilliseconds()));}
Date.prototype.$addDays=function(n){return new Date(this.valueOf()+n*24*3600*1000);}
Date.prototype.$addWeeks=function(n){return new Date(this.valueOf()+n*7*24*3600*1000);}
Date.prototype.$naturalDate=function(){return this.getFullYear()+"-"+("00"+(this.getMonth()+1)).slice(-2)+"-"+("00"+this.getDate()).slice(-2);}

function diffDays(d1,d2){return ~~(Math.abs(d1-d2)/1000/3600/24);}

function localDateStringToDate(s){return new Date(s+"T00:00:00");}


var periodStart="2015-04-09",periodEnd="2015-07-05",
    periodLength=diffDays(localDateStringToDate(periodStart),localDateStringToDate(periodEnd))+1;

persist=persist.create({
	dir:cmn.persistdir+"/datumpjeprik",
	continuous:false,
	interval:false
});
persist.initSync();

function ensureInitialised(){
	var days;
	days=persist.getItem("days");
	if(!days||days.length!=periodLength){
		days=Array.apply(null,new Array(periodLength)).map(function(){return 0;});
		persist.setItemSync("days",days);
	}
}
ensureInitialised();

module.exports=function(app,io,moddir){
	app.get("/datumpjeprik",function(req,res){
		res.set("Content-Type","text/html");
		res.sendFile(moddir+"/datumpjeprik.html");
	});
	app.get("/datumpjeprik/dates",function(req,res){
		res.set("Content-Type","text/json");
		res.send('{"periodStart":"'+periodStart+'","periodEnd":"'+periodEnd+'"}');
	});
	app.get("/datumpjeprik/days",function(req,res){
		ensureInitialised();
		res.set("Content-Type","text/json");
		res.send(persist.getItem("days"));
	});
	app.post("/datumpjeprik/adddays",function(req,res){
		var newdays;
		console.log(req.body);
		try{
			newdays=JSON.parse(req.body);
			if(newdays.length!=periodLength)throw new Error("length mismatch");
			if(!newdays.map(function(v){return typeof v=="boolean";}).reduce(function(a,b){return a&&b;}))throw new Error("not all bools");
			ensureInitialised();
			persist.setItemSync("days",persist.getItem("days").map(function(v,i){return v+newdays[i];}));
			res.send("true");
		} catch(e){
			res.send("[false,\""+e.message+"\"]");
			return;
		}
	});
};