import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';
import {Sites} from "./sites";
import { Roles } from 'meteor/alanning:roles';

export const Students = new Mongo.Collection('students');

if (Meteor.isServer) {
	Students.createIndex({id: 1}, {name: "External ID", unique: true});

	// This code only runs on the server
	Meteor.publish('students', function(siteId) {
		return Students.find({siteId});
	});
}

Meteor.methods({
	/**
	 * Sets a first name alias that can be overridden by the one that is imported.
	 * @param _id The student's database ID.
	 * @param alias The alias to set for the student.
	 */
	'students.setAlias'(_id, alias) {
		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			check(_id, String);
			check(alias, String);

			Students.update({_id}, !alias || !alias.length() ? {$unset: {alias: true}} : {$set: {alias}});
		}
	},
	/**
	 * Expects the CSV string to contain comma delimited data in the form:
	 * email, student ID, first name, last name, grade, first name alias, last name alias
	 *
	 * The query in Aeries is: `LIST STU SEM ID FN LN GR FNA LNA`.
	 * The query in SQL is: `SELECT [STU].[SEM] AS [StuEmail], [STU].[ID] AS [Student ID], STU.FN AS [First Name], STU.LN AS [Last Name], [STU].[GR] AS [Grade], [STU].[FNA] AS [First Name Alias], [STU].[LNA] AS [Last Name Alias] FROM (SELECT [STU].* FROM STU WHERE [STU].DEL = 0) STU WHERE ( [STU].SC = 5) ORDER BY [STU].[LN], [STU].[FN];`.
	 * Run the query in Aeries as a `Report`, select TXT, and upload here.
	 *
	 * Aeries adds a header per 'page' of data (I think 35 entries per page).
	 * Example:
	 * Anderson Valley Jr/Sr High School,6/11/2022
	 * 2021-2022,Page 1
	 * StuEmail,Student ID,First Name,Last Name,Grade,First Name Alias,Last Name Alias
	 */
	'students.loadCsv'(csv, siteId) {
		if(Roles.userIsInRole(Meteor.userId(), "admin", {anyScope:true})) {
			check(csv, String);
			check(siteId, String);

			let site = Sites.findOne({_id: siteId});

			if(site) {
				let lines = csv.split(/\r?\n/);
				let pageHeader = lines[0];
				let skip;

				for (const line of lines) {
					if (skip > 0) skip--;
					else if (line === pageHeader) {
						skip = 2;
					} else {
						let values = line.split(/\s*,\s*/);

						if(values.length === 7) {
							let email = values[0];
							let id = values[1];
							let firstName = values[2];
							let lastName = values[3];
							let grade = parseInt(values[4], 10);
							let firstNameAlias = values[5];
							let active = true;
							let student = {siteId, email, id, firstName, lastName, grade, firstNameAlias, active};

							// console.log(student);
							// Update or insert in the db.
							Students.upsert({id}, {$set: student});
						}

						//TODO: Find existing student.  Update student, and move them to the new site.
						//TODO: Create student if none exists.
					}
				}
			}
		}
	}
});
