var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cookieSession = require('cookie-session');
var flash = require('connect-flash');
var Flukso = require("./flukso");
var IpPoll = require("./ip-poll");
var CTDOApi = require("./ctdo-api");
var routes = require("./routes");
var path = require('path');
var mqttClient = require('mqtt');

var spaceanswer = {
    api: "0.13",
    ext_ccc: "erfa",
    space: "Chaostreff Dortmund",
    logo: "https://www.chaostreff-dortmund.de/presse/logo/logo_ctdo.png",
    icon: {
        open: "https://status.ctdo.de/img/green.png",
        closed: "https://status.ctdo.de/img/red.png"
    },
    url: "https://www.chaostreff-dortmund.de/",
    location: {
        address: "Braunschweiger Str 22, 44145 Dortmund, Germany",
        lon: 7.4649449,
        lat: 51.527611
    },
    contact: {
        phone: "+49 231 8 404 777",
        irc: "irc://irc.hackint.eu/#ccc.do",
        ml: "discuss@lists.chaostreff-dortmund.de",
        twitter: "@ctdo",
        issue_mail: "server-admin@chaostreff-dortmund.de"
    },
    issue_report_channels: ["issue_mail"],
    state: {
        open: null,
        lastchange: 0,
        icon: {
            open: "https://status.ctdo.de/img/green.png",
            closed: "https://status.ctdo.de/img/red.png"
        }
    },
    feeds: {
        blog: {
            type: "application/rss+xml",
            url: "https://www.chaostreff-dortmund.de/feed/"
        },
        calendar: {
            type: "ical",
            url: "https://www.chaostreff-dortmund.de/events.ics"
        }
    },
    sensors: {
        power_consumption: [{
            unit: "W",
            name: "mains power",
            description: "overall power consumption from our space",
            location: "basement",
            value: 0
        }],
		people_now_present: [{
			value: 0,
			names: []
		}]
    }
};
var simpleanswer = {state: "unknown", count: 0, names: [], lastchange: 0, power: 0};
var usercountanswer = {
    at: 0, current_value: 0, datapoints: []
};

var ippoll = new IpPoll("rpi3.raum.ctdo.de");
var ctdoapi = new CTDOApi("api.ctdo.de/names.php");
var flukso = new Flukso("flukso.raum.ctdo.de", "/sensor/cf00e0b22230f4a8870af58f2b8719dd");
var mqtt = mqttClient.connect('mqtt://raum.ctdo.de');
var connected = false;

var port = '9911';
var address = 'localhost';

ctdoapi.on('done', function (answer) {
    simpleanswer.count = answer.count;
    simpleanswer.names = answer.names;

	spaceanswer.sensors.people_now_present[0].value = answer.count;
	spaceanswer.sensors.people_now_present[0].names = answer.names;

    if (usercountanswer.datapoints.length > 20) {
        usercountanswer.datapoints.shift();
    }

    usercountanswer.datapoints.push({at: new Date().getTime(), value: simpleanswer.count});
});

ippoll.on('doneState', function (state) {
    spaceanswer.state.open = state;
    spaceanswer.state.lastchange = Math.floor(new Date().getTime() / 1000);
    simpleanswer.state = state;
    simpleanswer.lastchange = spaceanswer.state.lastchange;
    simpleanswer.lastchange = new Date().getTime();
    io.sockets.emit('sdata', {data: simpleanswer});
});

flukso.on('done', function (num) {
    simpleanswer.power = num;
    spaceanswer.sensors.power_consumption[0].value = num;
    io.sockets.emit('sdata', {data: simpleanswer});
});

flukso.on('failed', function (error) {
    console.log("Flukso: " + error);
});

mqtt.on('connect', function () {
    console.log("connected to mqtt");
    mqtt.subscribe('raumstatus/simple');
});

mqtt.on('message', function (topic, message) {
    if (topic === 'raumstatus/simple') {
        connected = (message.toString() === 'true');
    }
});

function sendSimple() {
    mqtt.publish('raumstatus/simple', JSON.stringify(simpleanswer));
}

function work() {
    ctdoapi.poll();
    ippoll.pollState();
    sendSimple();
}

setInterval(work, 60000);
work();

setInterval(flukso.pollPower, 5000);
flukso.pollPower();

app.use(express.static('public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));
app.use(cookieSession({secret: 'ctdo', cookie: {maxAge: 60000}}));
app.use(flash());

app.set('/views');
app.set('view engine', 'jade');
app.disable('x-powered-by');
app.enable('trust proxy');

app.get('/api/spaceapi/v13', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Cache-Control", "no-cache");
    res.send(spaceanswer);
});

app.get('/api/simple/v2', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Cache-Control", "no-cache");
    res.send(simpleanswer);
});

app.get('/api/usercount', function (req, res) {
    usercountanswer.at = simpleanswer.lastchange;
    usercountanswer.current_value = simpleanswer.count;
    res.send(usercountanswer);
});

function getstatusImage(req, res) {
    if (spaceanswer.state.open == true) {
        res.sendFile(path.resolve(__dirname, 'public/img/green.png'));
    } else if (spaceanswer.state.open == false) {
        res.sendFile(path.resolve(__dirname, 'public/img/red.png'));
    } else {
        res.sendFile(path.resolve(__dirname, 'public/img/yellow.png'));
    }
}

app.get('/api/simple/image', function (req, res) {
    getstatusImage(req, res);
});

app.get('/api/simple/image.png', function (req, res) {
    getstatusImage(req, res);
});

//app.get('/db', routes.db);
//app.post('/form', routes.form);
app.get('/', routes.index);

var server = server.listen(port, address, function (err) {
    if (err) {
        console.log(err);
    }

    var message = 'Server is running @ http://' + address + ':' + port;
    console.log(message);
});
