#!/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 HarvestableTemplateId,LastHarvest,ContainerName,AreaId from containerList WHERE Name=?',(username,))
	rows = c.fetchall()
	containerList = []

	for row in rows:
		harvestableTemplateId=row[0]
		lastHarvest=row[1]
		containerName=row[2]
		areaId=row[3]
		
		c.execute('SELECT ItemTemplateId,UpdateTime,SlotIndex,HarvestableName from harvestablesList WHERE Name=? AND ParentContainerName=? AND AreaId=?',(username,containerName,areaId))
		rows2 = c.fetchall()
		harvestablesList = []
		for row2 in rows2:
			harvestable = {'itemTemplateId':row2[0],'updateTime':row2[1],'index':row2[2],'harvestableName':row2[3]}
			harvestablesList.append(harvestable)
		
		
		containers = {'harvestableTemplateId':harvestableTemplateId, 'lastHarvest':lastHarvest, 'containerName':containerName, 'harvestables':harvestablesList, 'areaId':areaId}
		containerList.append(containers)
	

	result['containers'] = containerList
	


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

print(json.dumps(result))