<commit_before>"use strict";

const db = require('./db');
const env = require('../../env');
const outsideConditions = require('./outsideConditions');
const insideConditions = require('./insideConditions');
const socket = require('../socket');

let refreshInterval = 10; // minutes
let saveInterval = 30;
let currentValues;

db.getConnection(env.mongo.uri, (err, connection) => {
	connection.collection('ambientalConditions').find().sort({
		_id: -1
	}).limit(1).toArray((err, dbEntries) => {
		if (err) {
			init(null, null);
			return;
		}

		if (dbEntries && dbEntries.length) {
			currentValues = {
				inside: {
					temperature: dbEntries[0].i.t,
					humidity: dbEntries[0].i.h
				},
				outside: {
					temperature: dbEntries[0].o.t,
					humidity: dbEntries[0].o.h
				}
			};

			init(currentValues, dbEntries[0]._id);
		} else {
			init(null, null);
		}
	});
});


function init (lastValues, lastDate) {
	if (lastDate === null) {
		startRefresh();
	} else {
		setTimeout(startRefresh, lastDate.getTime() + refreshInterval * 60 * 1000 - new Date().getTime());
	}


	if (lastDate === null) {
		startSave();
	} else {
		setTimeout(startRefresh, lastDate.getTime() + saveInterval * 60 * 1000 - new Date().getTime());
	}
}

function startRefresh () {
	refresh();
	setInterval(refresh, refreshInterval * 60 * 1000);
}

function startSave () {
	save();
	setInterval(save, saveInterval * 60 * 1000);
}

function refresh () {
	outsideConditions.get().then((outData) => {
		insideConditions.get().then((inData) => {
			if (outData && inData) {
				currentValues = {
					inside: {
						temperature: inData.temperature,
						humidity: inData.humidity
					},
					outside: {
						temperature: outData.temperature,
						humidity: outData.humidity
					}
				};

				socket().emit('ambiental-conditions', currentValues);
			}
		});
	}).catch((e) => {
		console.log('error', e);
	});
}

function save () {
	db.getConnection(env.mongo.uri, (err, connection) => {
		connection.collection('ambientalConditions').insert({
			_id: new Date(),
			i: {
				t: currentValues.inside.temperature,
				h: currentValues.inside.humidity
			},
			o: {
				t: currentValues.outside.temperature,
				h: currentValues.outside.humidity
			}
		}, currentValues);
	});<commit_msg>Initial save race condition fixed.<commit_after>"use strict";

const db = require('./db');
const env = require('../../env');
const outsideConditions = require('./outsideConditions');
const insideConditions = require('./insideConditions');
const socket = require('../socket');

let refreshInterval = 10; // minutes
let saveInterval = 30;
let currentValues;

db.getConnection(env.mongo.uri, (err, connection) => {
	connection.collection('ambientalConditions').find().sort({
		_id: -1
	}).limit(1).toArray((err, dbEntries) => {
		if (err) {
			init(null, null);
			return;
		}

		if (dbEntries && dbEntries.length) {
			currentValues = {
				inside: {
					temperature: dbEntries[0].i.t,
					humidity: dbEntries[0].i.h
				},
				outside: {
					temperature: dbEntries[0].o.t,
					humidity: dbEntries[0].o.h
				}
			};

			init(currentValues, dbEntries[0]._id);
		} else {
			init(null, null);
		}
	});
});


function init (lastValues, lastDate) {
	startRefresh(() => {
		if (lastDate === null) {
			startSave();
		} else {
			setTimeout(startSave, lastDate.getTime() + saveInterval * 60 * 1000 - new Date().getTime());
		}
	});
}

function startRefresh (callback) {
	refresh(callback);
	setInterval(refresh, refreshInterval * 60 * 1000);
}

function startSave () {
	save();
	setInterval(save, saveInterval * 60 * 1000);
}

function refresh (callback) {
	outsideConditions.get().then((outData) => {
		insideConditions.get().then((inData) => {
			if (outData && inData) {
				currentValues = {
					inside: {
						temperature: inData.temperature,
						humidity: inData.humidity
					},
					outside: {
						temperature: outData.temperature,
						humidity: outData.humidity
					}
				};

				socket().emit('ambiental-conditions', currentValues);
			}

			callback();
		});
	}).catch((e) => {
		console.log('error', e);

		callback();
	});
}

function save () {
	if (currentValues) {
		db.getConnection(env.mongo.uri, (err, connection) => {
			connection.collection('ambientalConditions').insert({
				_id: new Date(),
				i: {
					t: currentValues.inside.temperature,
					h: currentValues.inside.humidity
				},
				o: {
					t: currentValues.outside.temperature,
					h: currentValues.outside.humidity
				}
			}, currentValues);
		});
	}
{'fraction_non_alphanumeric': 0.17003329633740288, 'fraction_numerical': 0.014206437291897892, 'mean_word_length': 3.391812865497076, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7228979', 'n_tokens_mistral': 1834, 'n_tokens_neox': 1460, 'n_words': 285}