import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';
import { MongoClient } from 'mongodb';
//import {Roles} from 'alanning/roles';

//export const Records = new Mongo.Collection('records');
let client;
let database;
let dataCollection;

if (Meteor.isServer) {
	// let uri = process.env.MONGO_URL2;
	// uri = "mongodb://localhost:27017";
	//
	// //client = new MongoClient(uri);
	// MongoClient.connect(uri, (err, c) => {
	// 	client = c;
	// 	database = client.db("avusd-data-collection");
	// 	dataCollection = database.collection("records");
	// 	dataCollection.find({deviceId: "1e3e99ef-adf4-4aa2-8784-205bc60f0ce3"}).toArray((e, a) => {
	// 		if(e) console.log(e);
	// 		else console.log("Found " + a.length + " records.");
	// 	})
	// });


	// let results = Meteor.Records.find({deviceId: "1e3e99ef-adf4-4aa2-8784-205bc60f0ce3"}).fetch();
	// console.log(results);
}

if (Meteor.isServer) {
	Meteor.methods({
		/**
		 * Collects Chromebook history given one of the possible parameters.
		 * @param params An object with a single attribute.  The attribute must be one of: deviceId, serial, email.  It will find all Chromebook data that starts with the given attribute value.
		 * @returns {any} Array of Chromebook data objects.
		 */
		'DataCollection.chromebookData'(params) {
			if(Roles.userIsInRole(Meteor.userId(), "laptop-management", {anyScope:true})) {
				let query = {};

				if (params.deviceId) query.deviceId = params.regex ? {
					$regex: params.deviceId,
					$options: "i"
				} : params.deviceId;
				else if (params.serial) query.serial = params.regex ? {
					$regex: params.serial,
					$options: "i"
				} : params.serial;
				else if (params.email) query.email = params.regex ? {
					$regex: params.email,
					$options: "i"
				} : params.email;

				// console.log("Collecting Chromebook Data: ");
				// console.log(query);
				let result = Meteor.Records.find(query).fetch();
				// console.log("Found: ");
				// console.log(result);

				return result;
			}
			else {return null;}
		}
		// 'tasks.setChecked'(taskId, setChecked) {
		//     check(taskId, String);
		//     check(setChecked, Boolean);
		//
		//     const task = Tasks.findOne(taskId);
		//     if (task.private && task.owner !== this.userId) {
		//         // If the task is private, make sure only the owner can check it off
		//         throw new Meteor.Error('not-authorized');
		//     }
		//
		//     Tasks.update(taskId, { $set: { checked: setChecked } });
		// },
		// 'tasks.setPrivate'(taskId, setToPrivate) {
		//     check(taskId, String);
		//     check(setToPrivate, Boolean);
		//
		//     const task = Tasks.findOne(taskId);
		//
		//     // Make sure only the task owner can make a task private
		//     if (task.owner !== this.userId) {
		//         throw new Meteor.Error('not-authorized');
		//     }
		//
		//     Tasks.update(taskId, { $set: { private: setToPrivate } });
		// },
	});
}
