import sys
import shutil
import json
import os
from addContextClass import addNewClass

""" Script called by the server to add a new context class and dump it to disk """

print("--- server_add_context_class ---")

# Get the first param:
filenameTmp = str(sys.argv[1]) # Classifer that we received from the client (the one that should be adapted)
filenameClassifier = str(sys.argv[2]) # Filename where we will stored the adapted classifier
newClassName = str(sys.argv[3])

oldGMM = json.load(open(filenameTmp,"rb"))

print("Incorporating the new class " + newClassName)
newGMM = addNewClass(oldGMM, newClassName)

print("Incorporation of context class " + newClassName + " finished")

# Dump the adapted GMM into the right location:
json.dump(newGMM, open(filenameClassifier, "wb"))

os.remove(filenameTmp)
for i in range(len(sortedList)):
    sortedList[i][1] = i

#print(sortedList)

# Convert back to dictionary:
newClassesDict = {}
for el in sortedList:
    newClassesDict[el[0]] = el[1]

# Assign the new classesDict to all elements in the model:
for el in newGMM:
    el["classesDict"] = newClassesDict

""" Incorporate new classes: """
classesToBeAdded = []
for el in newClasses:
    if el not in oldClasses:
        classesToBeAdded.append(el)
        
for el in classesToBeAdded:
    print("Adding class " + el)
    newGMM = addNewClass(newGMM, el)

json.dump(newGMM, open(new_filename, "wb"))
os.remove(old_filename) 

print("Manage classes finished: " + str(len(classesToBeAdded)) + " class(es) added and " + str(numberClassesDelete) + " class(es) removed")