import main
import unittest
import copy
import json
import flask
from pymongo import MongoClient
import datetime

def areDicsEqual(dic1, dic2):
	if len(dic1) != len(dic2):
		print(dic1)
		print(dic2)
		return False
	for k in dic1:
		if k not in dic2:
			print(dic1)
			print(dic2)
			return False

		# Incase one was an ObjectID and the other was a string representation of the object id, cast both to string for evaluation
		if str(dic1[k]) != str(dic2[k]):
			print(dic1)
			print(dic2)
			return False
	return True

class NYCSLTestCase(unittest.TestCase):
	def setUp(self):
		main.db = MongoClient().test
		self.db = main.db
		self.app = main.app.test_client()

	def tearDown(self):
		MongoClient().drop_database("test")

EXAMPLE_USER = {"_id": "1", "name": "Michael Truell"}
EXAMPLE_SCHOOL = {"_id": "asdlfkj", "name": "Horace Mann School"}

class UserTestCase(NYCSLTestCase):
	def testGetAll(self):
		assert b'[]' in self.app.get("/users").data

		exampleUser = copy.deepcopy(EXAMPLE_USER)
		self.db.user.insert_one(exampleUser)
		newUser = json.loads(self.app.get("/users").data.decode("utf-8"))[0]
		assert areDicsEqual(exampleUser, newUser)

	def testGet(self):
		assert self.app.get("/users/1").status_code == 404

		exampleUser = copy.deepcopy(EXAMPLE_USER)
		self.db.user.insert_one(exampleUser)
		newUser = json.loads(self.app.get("/users/"+str(exampleUser['_id'])).data.decode("utf-8"))
		assert areDicsEqual(exampleUser, newUser)

	def testPost(self):
		exampleUser = copy.deepcopy(EXAMPLE_USER)
		exampleSchool = copy.deepcopy(EXAMPLE_SCHOOL)

		assert self.db.user.find_one(exampleUser) is None

		# Try posting without having logged in via github
		args = {"schoolID": exampleSchool["_id"], "userID": exampleUser["_id"]}
		req = self.app.post("/users", data=json.dumps(args), content_type="application/json")