127.0.0.1:8000 smart-home-server / master server / utils / location.js
master

Tree @master (Download .tar.gz)

location.js @masterraw · history · blame

const utils = require('.');
const actions = require('./actions');

const locations = utils.enumify(["home", "work", "away"]);
console.log("Possible locations:", locations);

function count(location) {
    return utils.query("SELECT user_id FROM location WHERE ?", {
        location: location
    }).then(function(rows) {
        console.log("There are", rows.length, "people at", location);
        return rows.length;
    });
}

function check(user_id, location) {
    return utils.query("SELECT * FROM location WHERE user_id=? AND location=?", [
        user_id, location
    ]).then(function(rows) {
        return rows.length > 0;
    }).catch(console.error);
}

let num_home = {
    curr: 0,
    prev: 0
};

count(locations.home).then(function(total) {
    num_home.prev = total;
    num_home.curr = total;
});

module.exports = {
    coords: {
        home: {
            // 2610 Hampshire Rd, Cleveland Heights, OH 44106
            lat: 41.507886,
            long: -81.586484
        }
    },
    enum: locations,
    num_home: function() {
        return num_home;
    },
    count: count,
    check: check,
    update: function(location, user_id) {
        return utils.query("SELECT location FROM location WHERE user_id=?", [
            user_id
        ]).then(function(rows) {
            const prev_location = rows[0].location;
            if (location !== prev_location) {
                return utils.query("UPDATE location SET location=? WHERE user_id=?", [
                    location, user_id
                ]).then(function() {
                    console.log("prev num_home values", num_home);
                    num_home.prev = num_home.curr;
                    if (prev_location === locations.home) {
                        num_home.curr--;
                    } else if (location === locations.home) {
                        num_home.curr++;
                    } // else dont modify. Ex: away -> work
                    console.log("new num_home values", num_home);
                    actions.check("location");
                });
            } // else don't update anything
        });
    }
};