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

print("Content-Type: application/json")
print("")
method = os.environ["REQUEST_METHOD"]
if method != "POST":
	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 TryRetrive():
	username = jsonData['name'].lower()
	answer = jsonData['answer'].lower()
	authToken = jsonData['authToken']
	
	#Check User Exists
	c = db.cursor()
	c.execute('SELECT COUNT(1) from users WHERE Name=?',(username,))
	rows = c.fetchone()
	count = rows[0]
	
	if count == 0:
		result['status'] = USER_DOES_NOT_EXIST
		return 0
	#Check Answer
	c.execute('SELECT AnswerHash from securityQuestion WHERE Name= ?',(username,))
	rows = c.fetchone()
	AnswerHash = rows[0]
	
	c.execute('SELECT Salt from users WHERE Name=?',(username,))
	rows = c.fetchone()
	Salt = rows[0]

	InputHash = pass_salt_algo(answer, Salt)
	
	if InputHash != AnswerHash:
		result['status'] = INVALID_PASSWORD
		return 0
	
	# Set new password
	# Unlike bandai, we store our passwords securely
	newPass = answer
	if len(answer) < 9:
		newPass += str(random.randint(0,999))
	
	NewPassHash = pass_salt_algo(newPass, Salt)
	
	c.execute('UPDATE users SET PassHash=? WHERE Name=?',(NewPassHash,username))
	c.execute('UPDATE users SET LastSession=NULL WHERE Name=?',(username,))
	
	result['password'] = newPass

db = DbConnect()
TryRetrive()
db.commit()
db.close()
print(json.dumps(result))
		

	