#!/usr/bin/python3
from dreamtown_config import *
import sys
import binascii
import os
import json
import sqlite3
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 TrySave():
	Containers = jsonData['containers']
	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]
	
	for Container in Containers:
		harvestableTemplateId = Container['harvestableTemplateId']
		lastHarvest = Container['lastHarvest']
		containerName = Container['containerName']
		harvestables = Container['harvestables']
		areaId = Container['areaId']
		
		for harvestable in harvestables:
			itemTemplateId = harvestable['itemTemplateId']
			updateTime = harvestable['updateTime']
			index = harvestable['index']
			harvestableName = harvestable['harvestableName']
			
			c.execute('DELETE from harvestablesList where Name=? and HarvestableName=? and AreaId=? and ParentContainerName=?',(username,harvestableName,areaId,containerName))
			c.execute('INSERT INTO harvestablesList VAlUES (?,?,?,?,?,?,?)',(username,itemTemplateId,updateTime,Index,harvestableName,areaId,containerName))
			
		c.execute('DELETE from containerList where Name=? and AreaId=? and ContainerName=?',(username,areaId,containerName))
		c.execute('INSERT INTO containerList VAlUES (?,?,?,?,?)',(username,harvestableTemplateId,lastHarvest,containerName,areaId))


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

print(json.dumps(result))