#!/usr/bin/python3
from dreamtown_config import *
import sys
import binascii
import os
import json
import sqlite3
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 TrySave():
	CharacterIds = jsonData['characterIds']
	ActualCharacterId = jsonData['actualCharacterId']
	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 CharacterId in CharacterIds:
		c.execute('DELETE from characterList where Name=? AND CharacterId=?',(username,CharacterId))
		c.execute('INSERT INTO characterList VAlUES (?,?,NULL)',(username,CharacterId))
	c.execute('DELETE from characterList WHERE Name=? and actualCharacterId IS NOT NULL',(username,))
	c.execute('INSERT INTO characterList VAlUES (?,NULL,?)',(username,ActualCharacterId))



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

print(json.dumps(result))