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

PrintHeaders()
EnsurePost()


content_len = int(os.environ["CONTENT_LENGTH"])
post = sys.stdin.read(content_len)
jsonData = json.loads(post)
result = {"status":SUCCESS}
	
def TryGet():
	authToken = jsonData['authToken']
	
	c = db.cursor()
	c.execute('SELECT COUNT(1) from users WHERE LastSession=?',(authToken,))
	rows = c.fetchone()
	count = rows[0]
	if count == 0:
		result['status'] = USER_DOES_NOT_EXIST
		return 0
	
	#Find Username
	c.execute('SELECT Name from users WHERE LastSession=?',(authToken,))
	rows = c.fetchone()
	username = rows[0]
	
	c.execute('SELECT AreaId,LastVisit,NextRubishSpawnTime from areaList WHERE Name=?',(username,))
	rows = c.fetchall()
	areaList = []
	for row in rows:
		area = {}
		#'areaId':row[0], 'lastVisit':row[1], 'nextRubishSpawnTime':row[2]
		if row[0] != None:
			area['areaId'] = row[0]
		if row[1] != None:
			area['lastVisit'] = row[1]
		if row[2] != None:
			area['nextRubishSpawnTime'] = row[2]
		if not (row[0] == None and row[1] == None and row[2] == None): 
			areaList.append(area)
	c.execute('SELECT ActualAreaId from areaList WHERE Name=? and ActualAreaId IS NOT NULL',(username,))
	rows = c.fetchone()
	actualAreaId = rows[0]
	result['actualAreaId'] = actualAreaId
	result['areas'] = areaList
	


try: 
	db = DbConnect()
	TryGet()
	db.commit()
	db.close()
except Exception as e:
	raise e
	os._exit(0)

print(json.dumps(result))