# coding: utf-8

import os
import os.path
import codecs

import json
import time


#----------------------------------------------------------
class Database_cl(object):
#----------------------------------------------------------

   # alle Elemente werden zur Laufzeit des Servers zur Vereinfachung auch im
   # Hauptspeicher abgelegt

   # die nächste zu vergebende Id wird ebenfalls dauerhaft gespeichert

   # zur Vereinfachung wird hier fest vorgegebenen, dass sich die Daten
   # im Unterverzeichnis "data" befinden

   #-------------------------------------------------------
   def __init__(self):
   #-------------------------------------------------------
      self.data_o = {}
      self.readData_p()

   #-------------------------------------------------------
   def createTopic_px(self, data_opl):
   #-------------------------------------------------------
      # Überprüfung der Daten müsste ergänzt werden!
      id_ = self.nextTopicId_p()
      self.data_o['topics'][str(id_)] = data_opl
      
      file_o = codecs.open(os.path.join('data', 'topics.dat'), 'w', 'utf-8')
      file_o.write(json.dumps(self.data_o['topics']))
      file_o.close()

      return id_
      
   #-------------------------------------------------------
   def createDiscussion_px(self, tId, data_opl):
   #-------------------------------------------------------
      # Überprüfung der Daten müsste ergänzt werden!
      id_ = self.nextDiscussionId_p()
      self.data_o['discussions'][id_] = data_opl
      self.data_o['topics'][tId]['discs'].append(id_)
      
      file_o = codecs.open(os.path.join('data', 'discussions.dat'), 'w', 'utf-8')
      file_o.write(json.dumps(self.data_o['discussions']))
      file_o.close()
      
      file_o = codecs.open(os.path.join('data', 'topics.dat'), 'w', 'utf-8')
      file_o.write(json.dumps(self.data_o['topics']))
      file_o.close()      
      
      return id_
   
   #-------------------------------------------------------
   def createPost_px(self, dId, data_opl):
   #-------------------------------------------------------
      # Überprüfung der Daten müsste ergänzt werden!
      
      id_ = self.nextPostId_p()
      self.data_o['posts'][id_] = data_opl
      self.data_o['discussions'][dId]['posts'].append(id_)
      
      file_o = codecs.open(os.path.join('data', 'posts.dat'), 'w', 'utf-8')
      file_o.write(json.dumps(self.data_o['posts']))
      file_o.close()
      
      file_o = codecs.open(os.path.join('data', 'discussions.dat'), 'w', 'utf-8')
      file_o.write(json.dumps(self.data_o['discussions']))
      file_o.close()      
      
      return id_   
         
      
   #-------------------------------------------------------
   def readTopic_px(self, id_ = None):
   #-------------------------------------------------------
      # hier zur Vereinfachung:
      # Aufruf ohne id: alle Einträge liefern
      data_o = None
      if id_ == None:
         data_o = self.data_o['topics']
      elif str(id_) == '0':
         data_o = self.getDefaultTopic_px()
      else:
         if str(id_) in self.data_o['topics']:
            data_o = self.data_o['topics'][str(id_)]
            
      return data_o
   
   #-------------------------------------------------------
   def readDiscussion_px(self, tId, dId = None):
   #-------------------------------------------------------
      # hier zur Vereinfachung:
      # Aufruf ohne id: alle Einträge liefern
      data_o = None
      if dId == None:
         data_o = {}
         discs = self.data_o['discussions']
         indices = self.data_o['topics'][str(tId)]['discs']
         for index in indices:
            data_o[index] = discs[index]
      elif str(dId) == '0':
         data_o = self.getDefaultDiscussion_px()
      else:
         if str(dId) in self.data_o['discussions']:
            data_o = self.data_o['discussions'][str(dId)]
            
      return data_o
   
   #-------------------------------------------------------
   def readPost_px(self, dId, pId = None):
   #-------------------------------------------------------
      # hier zur Vereinfachung:
      # Aufruf ohne id: alle Einträge liefern
      data_o = None
      if pId == None:
         data_o = {}
         posts = self.data_o['posts']
         indices = self.data_o['discussions'][str(dId)]['posts']
         for index in indices:
            data_o[index] = posts[index]
      elif str(pId) == '0':
         data_o = self.getDefaultPost_px()
      else:
         if str(pId) in self.data_o['posts']:
            data_o = self.data_o['posts'][str(pId)]
            
      return data_o

   #-------------------------------------------------------
   def updateTopic_px(self, id_, data_opl):
   #-------------------------------------------------------
      # Überprüfung der Daten müsste ergänzt werden!
      updated = False
      if id_ in self.data_o['topics']:
         for key in data_opl:
            self.data_o['topics'][id_][key] = data_opl[key]
         
         # Datei aktualisieren
         file_o = codecs.open(os.path.join('data', 'topics.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['topics']))
         file_o.close()

         updated = True
      
      return updated
   
   #-------------------------------------------------------
   def updateDiscussion_px(self, id_, data_opl):
   #-------------------------------------------------------
      # Überprüfung der Daten müsste ergänzt werden!
      updated = False
      if id_ in self.data_o['discussions']:
         for key in data_opl:
            self.data_o['discussions'][id_][key] = data_opl[key]
            
         # Datei aktualisieren
         file_o = codecs.open(os.path.join('data', 'discussions.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['discussions']))
         file_o.close()
         
         updated = True
            
      return updated
   
   #-------------------------------------------------------
   def updatePost_px(self, id_, data_opl):
   #-------------------------------------------------------
      # Überprüfung der Daten müsste ergänzt werden!
      updated = False
      if id_ in self.data_o['posts']:
         for key in data_opl:
            self.data_o['posts'][id_][key] = data_opl[key]
            
         # Datei aktualisieren
         file_o = codecs.open(os.path.join('data', 'posts.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['posts']))
         file_o.close()
         
         updated = True
         
      return updated

   #-------------------------------------------------------
   def deleteTopic_px(self, id_):
   #-------------------------------------------------------
      deleted = False
      if id_ in self.data_o['topics']:
         self.data_o['topics'][id_]['deleted'] = True
         for key in self.data_o['topics'][id_]['discs']:
            del self.data_o['discussions'][key]
         self.data_o['topics'][id_]['discs'] = []
         
         # Dateien aktualisieren
         file_o = codecs.open(os.path.join('data', 'topics.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['topics']))
         file_o.close()
         
         file_o = codecs.open(os.path.join('data', 'discussions.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['discussions']))
         file_o.close()         

         deleted = True
      
      return deleted
      
   #-------------------------------------------------------
   def deleteDiscussion_px(self, id_):
   #-------------------------------------------------------
      deleted = False
      if id_ in self.data_o['discussions']:
         self.data_o['discussions'][id_]['deleted'] = True
         for key in self.data_o['discussions'][id_]['posts']:
            del self.data_o['posts'][key]
         self.data_o['discussions'][id_]['posts'] = []
         
         # Dateien aktualisieren
         file_o = codecs.open(os.path.join('data', 'discussions.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['discussions']))
         file_o.close()
         
         file_o = codecs.open(os.path.join('data', 'posts.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['posts']))
         file_o.close()         
         
         deleted = True
         
      return deleted
   
   #-------------------------------------------------------
   def deletePost_px(self, id_):
   #-------------------------------------------------------
      deleted = False
      if id_ in self.data_o['posts']:
         self.data_o['posts'][id_]['deleted'] = True
         
         # Datei aktualisieren
         file_o = codecs.open(os.path.join('data', 'posts.dat'), 'w', 'utf-8')
         file_o.write(json.dumps(self.data_o['posts']))
         file_o.close()        
         
         deleted = True
         
      return deleted   
            

   #-------------------------------------------------------
   def getDefaultTopic_px(self):
   #-------------------------------------------------------

      return {
         'name' : '',
         'owner': '',
         'deleted': False,
         'discs': []
      }
   
   #-------------------------------------------------------
   def getDefaultDiscussion_px(self):
   #-------------------------------------------------------
   
      return {
         'name' : '',
         'owner': '',
         'deleted': False,
         'posts': []
      }
   
   #-------------------------------------------------------
   def getDefaultPost_px(self):
   #-------------------------------------------------------
      return {
         'title' : '',
         'text' : '',
         'owner': '',
         'time': time.localtime(),
         'deleted': False,
      }
   
   #-------------------------------------------------------
   def getUsers_px(self):
   #-------------------------------------------------------

      return self.data_o['users']
   
   #-------------------------------------------------------
   def saveUsers_px(self, data_o):
   #-------------------------------------------------------
      file_o = codecs.open(os.path.join('data', 'users.dat'), 'w', 'utf-8')
      file_o.write(json.dumps(self.data_o['users']))
      file_o.close()      

   #-------------------------------------------------------
   def readData_p(self):
   #-------------------------------------------------------

      files_a = os.listdir('data')
      for fileName_s in files_a:
         if fileName_s.endswith('.dat'):
            file_o = codecs.open(os.path.join('data', fileName_s), 'rU', 'utf-8')
            content_s = file_o.read()
            file_o.close()
            id_s = fileName_s[:-4]
            self.data_o[id_s] = json.loads(content_s)

   #-------------------------------------------------------
   def nextTopicId_p(self):
   #-------------------------------------------------------
      id_ = str(self.data_o['topics']['nextID'])
      nextID = int(self.data_o['topics']['nextID'])
      self.data_o['topics']['nextID'] = str(nextID + 1)

      return id_
   
   #-------------------------------------------------------
   def nextDiscussionId_p(self):
   #-------------------------------------------------------
      id_ = str(self.data_o['discussions']['nextID'])
      nextID = int(self.data_o['discussions']['nextID'])
      self.data_o['discussions']['nextID'] = str(nextID + 1)
      
      return id_
   
   #-------------------------------------------------------
   def nextPostId_p(self):
   #-------------------------------------------------------
      id_ = str(self.data_o['posts']['nextID'])
      nextID = int(self.data_o['posts']['nextID'])
      self.data_o['posts']['nextID'] = str(nextID + 1)
      
      return id_
      
db_o = Database_cl()
# EOF