# coding: utf-8

import os
import os.path
import codecs
import json
from datetime import datetime, timedelta

#----------------------------------------------------------
class Database_cl(object): 
#----------------------------------------------------------
    # da es hier nur darum geht, die Daten dauerhaft zu speichern,
    # wird ein sehr einfacher Ansatz verwendet:
    # - es können Daten zu genau 15 Teams gespeichert werden
    # - je Team werden 2 Teilnehmer mit Namen, Vornamen und Matrikelnummer
    #   berücksichtigt
    # - die Daten werden als eine JSON-Datei abgelegt
    

    #-------------------------------------------------------
    def __init__(self): 
    #-------------------------------------------------------
        self.data = {}
        self.data['Studenten'] = {}
        self.data['Lehrender'] = {}
        self.data['Firmen'] = {}
        self.data['Angebote'] = {}
        self.ReadAll()


    #------------------------------------------------------- 
    def Read(self, category):
    #-------------------------------------------------------
        path = 'data/' + category
        if not(os.path.exists(path)):
            os.makedirs(path)
        categoryDir = os.listdir(path)
        for fileName in categoryDir:
            if fileName.endswith('.json') and fileName != 'last.json':
                file = codecs.open(os.path.join('data', category, fileName), 'rU', 'utf-8')
                fileContent = file.read()
                id = fileName[:-5]
                self.data[category][id] = json.loads(fileContent)

    #------------------------------------------------------- 
    def ReadAll(self):
    #-------------------------------------------------------
        self.Read('Studenten')
        self.Read('Lehrender')
        self.Read('Firmen')
        self.Read('Angebote')    

    #-------------------------------------------------------
    def ReadEntry(self, category = None, id = None): 
    #-------------------------------------------------------
        print("ReadEntry: ", category, id)
        self.Read(category)
        data = None
        if id == None:
            data = self.data
        else:
            if id in self.data[category]: 
                data = self.data[category][id]
        
        print(data, "\n")
        return data

    #-------------------------------------------------------
    def Save(self, data, category): 
    #-------------------------------------------------------
        status_b = False
        id = data['id']
        print("ID: ", id, "\n")
        if(id != "None"):
            if id in self.data[category]:
                file = codecs.open(os.path.join('data', category, id+'.json'), 'w', 'utf-8')
                file.write(json.dumps(data, indent=3, ensure_ascii=True))
                file.close()
                self.Read(category)
                status_b = True
        else:
            data['id'] = self.IdNext(category)
            file = codecs.open(os.path.join('data', category, data['id']+'.json'), 'w', 'utf-8')
            file.write(json.dumps(data, indent=3, ensure_ascii=True))
            file.close()
            self.Read(category)
            status_b = True
        
        return status_b

    #-------------------------------------------------------
    def Delete(self, category, id): 
    #-------------------------------------------------------
        status_b = False
        if(category == 'Studenten'):
            for angebote in self.data['Angebote']:
                if(self.data['Angebote'][angebote]['Student'] == id):
                    try:
                        os.remove(os.path.join('data', 'Angebote', angebote+'.json'))
                    except OSError:
                        pass
        elif(category == 'Lehrender'):
            for angebote in self.data['Angebote']:
                if(self.data['Angebote'][angebote]['Lehrender'] == id):
                    try:
                        os.remove(os.path.join('data', 'Angebote', angebote+'.json'))
                    except OSError:
                        pass
        elif(category == 'Firmen'):
            for firmen in self.data['Firmen']:
                if(firmen == id):
                    fn = self.data['Firmen'][firmen]['Name']
            for angebote in self.data['Angebote']:
                if(self.data['Angebote'][angebote]['Firma'] == fn):
                    try:
                        os.remove(os.path.join('data', 'Angebote', angebote+'.json'))
                    except OSError:
                        pass

        if id in self.data[category]:
            os.remove(os.path.join('data', category, id+'.json'))
            del self.data[category][id]
        
        return status_b

    #-------------------------------------------------------
    def CheckOfferings(self, id): 
    #-------------------------------------------------------
        print("Offerings: ", id)
        for offerings in self.data['Angebote']:
            if(self.data['Angebote'][offerings]['Student'] != id):
                return 0
            else:
                return 1

    #-------------------------------------------------------
    def CheckDates(self): 
    #-------------------------------------------------------
        now = datetime.now()
        for offerings in self.data['Angebote']:
            if(self.data['Angebote'][offerings]['ZeitraumBis'] != ''):
                zeitraumBis = datetime.strptime(self.data['Angebote'][offerings]['ZeitraumBis'], "%d.%m.%Y")
                if(zeitraumBis <= now):
                    self.data['Angebote'][offerings]['Status'] = 'abgeschlossen'
                    data = {}
                    data['Status'] = 'abgeschlossen'
                    data['id'] = offerings
                    data['Name'] = self.data['Angebote'][offerings]['Name']
                    data['Firma'] = self.data['Angebote'][offerings]['Firma']
                    data['Beschreibung'] = self.data['Angebote'][offerings]['Beschreibung']
                    data['Voraussetzungen'] = self.data['Angebote'][offerings]['Voraussetzungen']
                    data['Firmenbetreuer'] = self.data['Angebote'][offerings]['Firmenbetreuer']
                    data['Lehrender'] = self.data['Angebote'][offerings]['Lehrender']
                    data['ZeitraumVon'] = self.data['Angebote'][offerings]['ZeitraumVon']
                    data['ZeitraumBis'] = self.data['Angebote'][offerings]['ZeitraumBis']
                    data['Student'] = self.data['Angebote'][offerings]['Student']
                    self.Save(data, 'Angebote')

    #-------------------------------------------------------
    def GetDefault(self, category): 
    #-------------------------------------------------------
        if(category == 'Studenten'):
            return {'Name':'', 'Vorname':'', 'Matrikelnummer':''}
        elif(category == 'Lehrender'):
            return {'Titel':'', 'Name':'', 'Vorname':'', 'Lehrgebiet':''}
        elif(category == 'Firmen'):
            return {'Name':'', 'Branche':'', 'Schwerpunkt':'', 'Sitz':'', 'Anzahl Mitarbeiter':''}
        elif(category == 'Angebote'):
            return {'Name':'', 'Firma':'', 'Beschreibung':'', 'Voraussetzungen':'', 'Firmenbetreuer':'', 'Status':'Angebot', 'Lehrender':'', 'ZeitraumVon':'', 'ZeitraumBis':'', 'Student':''}

    #-------------------------------------------------------
    def IdNext(self, category):
    #-------------------------------------------------------
        path = 'data/' + category + '/last.json'
        if(os.path.isfile(path)):
            file = open(os.path.join('data', category, 'last.json'), 'r+')
            last = file.read()
            last = str(int(last)+1)
            file.seek(0)
            file.write(last)
            file.close()
        else:
            file = open(os.path.join('data', category, 'last.json'), 'w+')
            last = str(int(0))
            file.write(last)
            file.close()
        return last
            
# EOF