#!/usr/bin/python3
from dreamtown_config import *
import sys
import binascii
import os
import json
import sqlite3
import hashlib
import time
import math

method = os.environ["REQUEST_METHOD"]
if method != "POST":
	print("Content-Type: application/json")
	print("")
	print("Expected POST")
	os._exit(1)
	

content_len = int(os.environ["CONTENT_LENGTH"])
post = sys.stdin.read(content_len)
jsonData = json.loads(post)
result = {"status":SUCCESS}



def CheckUserExists(username):
	c = db.cursor()
	c.execute('SELECT COUNT(1) from users WHERE Name=?',(username,))
	rows = c.fetchone()
	count = rows[0]
	return count

def TryCreate():
	username = jsonData['name'].lower()
	password = jsonData['password']
	authToken = jsonData['authToken']
	securityAnswer = jsonData['answer']
	questionType = jsonData['questionId']
	
	
	#Check name not in use allredy
		
	if CheckUserExists(username):
		result['status'] = NAME_ALREADY_USED
		i = 1;
		while True:
			newName = username + str(i)
			i += 1
			if CheckUserExists(newName) == 0:
				result['alternateName'] = newName
				break
			if i == 3000:
				result['alternateName'] = ""
				break
		return 0
	
	#Generate password hash
	Salt = binascii.hexlify(os.urandom(64)).decode('utf8')
	
	PassHashSalted = pass_salt_algo(password,Salt);
	AnswerHashSalted = pass_salt_algo(securityAnswer,Salt);
	
	c = db.cursor()
	c.execute('UPDATE users SET LastSession=NULL WHERE LastSession=?',(authToken,))
	c.execute('INSERT INTO users VAlUES (?,?,?,?,?)',(username,PassHashSalted,Salt,authToken,math.floor(time.time()*1000)))
	c.execute('INSERT INTO securityQuestion VAlUES (?,?,?)',(username,questionType,AnswerHashSalted))


db = DbConnect()
TryCreate()
db.commit()
db.close()

json = json.dumps(result)
print("Content-Type: application/json")
print("Content-Length: "+str(len(json)))
print("")
print(json)