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);
		
		// Convert the asset ID's to uppercase for storage to make searching easier.
		assetId = assetId.toUpperCase();

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			let assetType = AssetTypes.findOne({assetTypeId});
			
			if(Assets.findOne({assetId})) {
				//return {error: true, errorType: 'duplicateAssetId'}
				throw new Meteor.Error("duplicateAssetId", "Cannot use the same asset ID twice.")
			}
			else if(serial) {
				Assets.insert({assetTypeId, assetId, serial});
			}
			else {
				Assets.insert({assetTypeId, assetId});
			}
		}
	},
	'assets.update'(_id, assetId, serial) {
		check(_id, String);
		check(assetId, String);
		if(serial) check(serial, String);

		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			//TODO: Need to first verify there are no checked out assets to the staff member.
			Assets.update({_id}, {$set: {assetId, serial}});
		}
	},
	'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.
			Assets.remove({_id});
		}
	},
});

