import {Mongo} from "meteor/mongo";
import {Meteor} from "meteor/meteor";
import { check } from 'meteor/check';
import { Roles } from 'meteor/alanning:roles';
//import SimpleSchema from "simpl-schema";
import {AssetTypes} from "./asset-types";

export const Assets = new Mongo.Collection('assets');

/*
const AssetsSchema = new SimpleSchema({
	assetTypeId: {
		type: String,
		label: "Asset Type ID",
		optional: false,
		trim: true,
	},
	assetId: {
		type: String,
		label: "Asset ID",
		optional: false,
		trim: true,
		index: 1,
		unique: true
	},
	serial: {
		type: String,
		label: "Serial",
		optional: true,
		trim: false,
		index: 1,
		unique: false
	},
});
Assets.attachSchema(AssetsSchema);
 */

if (Meteor.isServer) {
	// Drop any old indexes we no longer will use.  Create indexes we need.
	//try {Assets._dropIndex("serial")} catch(e) {}
	Assets.createIndex({assetId: 1}, {name: "AssetID", unique: true});
	Assets.createIndex({serial: 1}, {name: "Serial", unique: false});

	// This code only runs on the server
	Meteor.publish('assets', function() {
		return Assets.find({});
	});
}
Meteor.methods({
	'assets.add'(assetTypeId, assetId, serial) {
		check(assetTypeId, String);
		check(assetId, String);
		check(serial, String);

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			let assetType = AssetTypes.findOne({assetTypeId});

			if(assetType.hasSerial && serial || !assetType.hasSerial && !serial) {
				if(serial) {
					Assets.insert({assetTypeId, assetId, serial});
				}
				else {
					Assets.insert({assetTypeId, assetId});
				}
			}
			else {
				//Should never get here due to client side validation.
				console.log("Error: Must provide a serial for asset types marked as having one, and may not provide one for asset types not marked as having one.")
			}
		}
	},
	'assets.remove'(_id) {
		check(_id, String);

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			//TODO: Need to first verify there are no checked out assets to the staff member.
		}
	},
});

