import cherrypy
from .database import Database_cl
from .view import View_cl
import collections
orderedDict = collections.OrderedDict()
from collections import OrderedDict

#----------------------------------------------------------
class Application_cl(object): 
#----------------------------------------------------------

#-------------------------------------------------------
# Request Processing
#-------------------------------------------------------

    #-------------------------------------------------------
    def __init__(self):
    #-------------------------------------------------------
        # spezielle Initialisierung können hier eingetragen werden
        self.db = Database_cl()
        self.view = View_cl()
    @cherrypy.expose

    #-------------------------------------------------------
    def index(self):
    #-------------------------------------------------------
        print("Index\n")
        return self.GenerateIndex()
    @cherrypy.expose

    #-------------------------------------------------------
    def category(self, cat=None):
    #-------------------------------------------------------
        print("Category: ", cat, "\n")
        if(cat==None):
            return self.GenerateIndex()
        else:
            return self.GenerateList(cat)
    @cherrypy.expose

    #-------------------------------------------------------
    def choice(self):
    #-------------------------------------------------------
        print("Choice \n")
        return self.GenerateListChoice()
    @cherrypy.expose

    #-------------------------------------------------------
    def eval(self, cat):
    #-------------------------------------------------------
        print("Eval \n")
        self.db.CheckDates()
        return self.GenerateListEval(cat)
    @cherrypy.expose

    #-------------------------------------------------------
    def detail(self, cat=None, id=None):
    #-------------------------------------------------------
        if(cat!=None):
            if(id!=None):
                print("Cat=", cat, " id=", id)
                return self.GenerateDetail(cat, id)
            else:
                print("ID=None Cat=", cat)
                return self.GenerateDetail(cat)
        else:
            return self.GenerateIndex()
    @cherrypy.expose

    #-------------------------------------------------------
    def detailchoice(self, id):
    #-------------------------------------------------------
        print("id=", id)
        return self.GenerateDetailChoice(id)

    @cherrypy.expose

    #-------------------------------------------------------
    def save(self, cat=None, **data):
    #-------------------------------------------------------
        print("Save: ", cat)
        dataTmp = data
        return self.GenerateSave(dataTmp, cat)
    @cherrypy.expose

    #-------------------------------------------------------
    def saveChoice(self, **data):
    #-------------------------------------------------------
        print("Save: Choice")
        dataTmp = data
        return self.GenerateSaveChoice(dataTmp)
    @cherrypy.expose

    #-------------------------------------------------------
    def delete(self, cat=None, id=None): 
    #-------------------------------------------------------
        print("Delete",cat,id)
        return self.GenerateDelete(cat, id)
    @cherrypy.expose
    
    #-------------------------------------------------------
    def default(self, *arguments, **kwargs): 
    #-------------------------------------------------------
        msg_s = "unbekannte Anforderung: " + \
                str(arguments) + \
                ''+ \
                str(kwargs)
        raise cherrypy.HTTPError(404, msg_s)
    default.exposed= True

#-------------------------------------------------------
# Functions
#-------------------------------------------------------

    #-------------------------------------------------------
    def GenerateIndex(self):
    #-------------------------------------------------------
        return self.view.CreateIndex()

    #-------------------------------------------------------
    def GenerateList(self, category):
    #-------------------------------------------------------
        self.db.ReadAll()
        data = {}
        data['content'] = {}
        data['headings'] = {}
        data['category'] = category
        data['content'] = self.db.data[category]
        if(len(data['content']) != 0):
            print(len(data['content']))
            contentFirst = list(data['content'].keys())[0]
            data['headings'] = list(data['content'][contentFirst].keys())
        print(data)
        return self.view.CreateList(data)

    #-------------------------------------------------------
    def GenerateListChoice(self):
    #-------------------------------------------------------
        self.db.ReadAll()
        data = {}
        data['content'] = {}
        offerings = self.db.data['Angebote']
        for key, value in offerings.items():
            for key2, value2 in value.items():
                if(key2 == 'Status'):
                    if(value2 == 'Angebot'):
                        data['content'][key] = value              

        print(data)
        return self.view.CreateListChoice(data)

    #-------------------------------------------------------
    def GenerateDetail(self, category, id=None):
    #-------------------------------------------------------
        self.db.ReadAll()
        data = {}
        data['category'] = category
        print("Detail",category,id)
        if(id != None):
            data['id'] = id
            data['content'] = self.db.ReadEntry(category, id)
        else:
            data['id'] = None
            data['content'] = self.db.GetDefault(category)
            print(data['content'])
        if(category == 'Angebote'):
            print("Angebote")
            data['Firmen'] = self.db.data['Firmen']
        print(data, "\n")
        return self.view.CreateDetail(data)

    #-------------------------------------------------------
    def GenerateDetailChoice(self, id):
    #-------------------------------------------------------
        self.db.ReadAll()
        data = {}
        data['id'] = id
        data = self.db.data['Angebote'][id]
        data['Studenten'] = self.db.data['Studenten']
        data['Lehrender'] = self.db.data['Lehrender']
        print(data, "\n")
        return self.view.CreateDetailChoice(data)

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

        data['category'] = cat
        if(cat == 'Firmen'):
            for keyFirma, valueFirma in sorted(Firmen.items()):
                data[valueFirma['Name']] = {}
                data[valueFirma['Name']]['Name'] = valueFirma['Name']
                data[valueFirma['Name']]['Angebote'] = {}
                data[valueFirma['Name']]['Angebote']['Angebot'] = {}
                data[valueFirma['Name']]['Angebote']['aktuell'] = {}
                data[valueFirma['Name']]['Angebote']['abgeschlossen'] = {}
                for keyAngebote, valueAngebote in Angebote.items():
                    if(valueAngebote['Firma'] == valueFirma['Name']):
                        data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']] = {}
                        data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']]['Name'] = valueAngebote['Name']
                        if(valueAngebote['Student'] != ''):
                            data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']]['Student'] = Studenten[valueAngebote['Student']]['Name']
                        else:
                            data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']]['Student'] = ''
                        if(valueAngebote['Lehrender'] != ''):
                            data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']]['Lehrender'] = Lehrender[valueAngebote['Lehrender']]['Name']
                        else:
                            data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']]['Lehrender'] = ''
                        data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']]['ZeitraumVon'] = valueAngebote['ZeitraumVon']
                        data[valueFirma['Name']]['Angebote'][valueAngebote['Status']][valueAngebote['Name']]['ZeitraumBis'] = valueAngebote['ZeitraumBis']
            print(data)
            return self.view.CreateListEval(data)
        elif(cat == 'Studenten'):
            for keyStudent, valueStudent in Studenten.items():
                data[valueStudent['Name']] = {}
                data[valueStudent['Name']]['Angebote'] = {}
                data[valueStudent['Name']]['Angebote']['Angebot'] = {}
                data[valueStudent['Name']]['Angebote']['aktuell'] = {}
                data[valueStudent['Name']]['Angebote']['abgeschlossen'] = {}
                for keyAngebot, valueAngebot in Angebote.items():
                    if(valueAngebot['Student'] == valueStudent['id']):
                        data[valueStudent['Name']]['Angebote'][valueAngebot['Status']][keyAngebot] = {}
                        data[valueStudent['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Lehrender'] = Lehrender[valueAngebot['Lehrender']]['Name']
                        data[valueStudent['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Status'] = valueAngebot['Status']
                        data[valueStudent['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Praxisphase'] = valueAngebot['Name']
                        data[valueStudent['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Firma'] = valueAngebot['Firma']
                        data[valueStudent['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['ZeitraumVon'] = valueAngebot['ZeitraumVon']
                        data[valueStudent['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['ZeitraumBis'] = valueAngebot['ZeitraumBis']
        elif(cat == 'Lehrender'):
            for keyLehrende, valueLehrende in Lehrender.items():
                data[valueLehrende['Name']] = {}
                data[valueLehrende['Name']]['Angebote'] = {}
                data[valueLehrende['Name']]['Angebote']['Angebot'] = {}
                data[valueLehrende['Name']]['Angebote']['aktuell'] = {}
                data[valueLehrende['Name']]['Angebote']['abgeschlossen'] = {}
                for keyAngebot, valueAngebot in Angebote.items():
                    if(valueAngebot['Lehrender'] == valueLehrende['id']):
                        data[valueLehrende['Name']]['Angebote'][valueAngebot['Status']][keyAngebot] = {}
                        data[valueLehrende['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Student'] = Studenten[valueAngebot['Student']]['Name']
                        data[valueLehrende['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Status'] = valueAngebot['Status']
                        data[valueLehrende['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Praxisphase'] = valueAngebot['Name']
                        data[valueLehrende['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['Firma'] = valueAngebot['Firma']
                        data[valueLehrende['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['ZeitraumVon'] = valueAngebot['ZeitraumVon']
                        data[valueLehrende['Name']]['Angebote'][valueAngebot['Status']][keyAngebot]['ZeitraumBis'] = valueAngebot['ZeitraumBis']

        return self.view.CreateListEval(data)


    #-------------------------------------------------------
    def GenerateSave(self, dataTmp, category):
    #-------------------------------------------------------
        if(category == None):
            return self.view.CreateIndex()
        else:
            self.db.Save(dataTmp, category)
            return self.GenerateList(category)

    #-------------------------------------------------------
    def GenerateSaveChoice(self, dataTmp):
    #-------------------------------------------------------
        if(dataTmp['Student'] != ''):
            angebote = self.db.CheckOfferings(dataTmp['Student'])
            print(angebote)
            if(angebote == 0):
                print("Save")
                self.db.Save(dataTmp, 'Angebote')
        return self.GenerateListChoice()

    #-------------------------------------------------------
    def GenerateDelete(self, category, id):
    #-------------------------------------------------------
        if(category == None or id == None):
            return self.view.CreateIndex()
        else:
            self.db.Delete(category, id)
            return self.GenerateList(category)

#EOF