# coding: utf-8

import os
import time
import codecs
import json

from app import stream

class manager_cl(object):
    exposed = True
    
    def __init__(self):
        self.stream = stream.stream_cl()    
        
    def LIST(self):
        chargenliste = {}
        filenames = os.listdir('data')
        for filename in filenames:
            if filename.endswith('.json'):
                charge = codecs.open(os.path.join('data', filename), 'r', 'utf-8')
                chargeData = eval(charge.read())
                charge.close()
                
                charge_id = filename[:-5]
                chargenliste[charge_id]={}
                chargenliste[charge_id]['chargeName'] = chargeData['info']['name']
        print(chargenliste)
        return json.dumps(chargenliste)
    
    def GET(self, nr):
        data = {}
        data = self.stream.loadCharge(nr)
        return json.dumps(data)
                 
    def RECEIVE(self, dieCharge):
        dieCharge = json.loads(dieCharge)
        if dieCharge['info']['chargenNr'] == -1:
            filenames = os.listdir('data')
            maxNr = 0
            for filename in filenames:
                if filename.endswith('.json'):
                    charge = codecs.open(os.path.join('data', filename), 'r', 'utf-8')
                    chargeData = eval(charge.read())
                    charge.close() 
                
                    if maxNr < chargeData['info']['chargenNr']:
                        maxNr = chargeData['info']['chargenNr']

            dieCharge['info']['chargenNr'] = maxNr + 1
            name = str(maxNr + 1)
            name += '.json'

            file = codecs.open(os.path.join('data', name), 'w', 'utf-8')
            file.write(json.dumps(dieCharge, indent = 3, ensure_ascii = True))
            file.close()
            
        else:
            name = str(dieCharge['info']['chargenNr'])
            name += '.json'
            
            file = codecs.open(os.path.join('data', name), 'w', 'utf-8')
            file.write(json.dumps(dieCharge, indent = 3, ensure_ascii = True))
            file.close()
    
    def DELETE(self, nr):
        path = 'data/'
        path += str(nr)
        path += '.json'
        print(path)
        
        os.remove(path)