import {Meteor} from "meteor/meteor";
import { _ } from 'underscore';
import { Roles } from 'meteor/alanning:roles';

// console.log("Setting Up Admin...")

if (Meteor.isServer) {
	Meteor.methods({
		'admin.fixRecords'(input) {
			if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
				console.log("In Fix Records");
				console.log("Deleting invalid records...");

				// Delete any records missing key fields.
				Meteor.Records.remove({serial: {$exists: false}});
				Meteor.Records.remove({deviceId: {$exists: false}});
				Meteor.Records.remove({endTime: {$exists: false}});

				console.log("Consolidating records...");

				let emails = _.uniq(Meteor.Records.find({}, {
					sort: {email: 1},
					fields: {email: true}
				}).fetch().map(function (x) {
					return x.email;
				}), true);

				emails.forEach(email => {
					// Find all records for the user sorted from oldest to newest.
					let records = Meteor.Records.find({email}, {sort: {startTime: 1}}).fetch();
					let newRecords = [];
					let record = records[0];

					for (let index = 1; index < records.length; index++) {
						let nextRecord = records[index];

						if (record.deviceId === nextRecord.deviceId) {
							record.endTime = nextRecord.endTime;
							record.count += nextRecord.count;
							record.internalCount += nextRecord.internalCount;
						} else {
							if (!record.endTime) record.endTime = nextRecord.startTime;
							newRecords.push(record);
							record = nextRecord;
						}
					}
					newRecords.push(record);

					Meteor.Records.remove({email});

					for (let index = 0; index < newRecords.length; index++) {
						Meteor.Records.insert(newRecords[index]);
					}
				});
			}
		},
	});
}

// console.log("Admin setup.")