from zope.interface import Interface, implements
from axiom import item, attributes, store
from epsilon import extime
import time, os, sys
from twisted.application import service
#from awum import appns

#<glyph> nextime: aStore.query(anItem, anItem.attribute.like(u'astring%'))
#-:- jpv950 [n=jpv@gw-ciist-lti.ist.utl.pt] has joined #python
#<nextime> thanks
#<glyph> nextime: Sorry that the interface documentation doesn't make that entirely clear.
#<|MUSE|:#python> habnabit: what does 'for a, b, *c in foo:' do?
#<glyph> nextime: There are also 'startswith' and 'endswith' methods, so in that case you could do aStore.query(anItem,
#          anItem.attribute.startswith(u'astring'))

class ISkyliveUsers(Interface):
   """ ISkyliveUsers Interface """

class SkyliveUsers(item.Item):
   
   implements(ISkyliveUsers)
   schemaVersion=2

   typeName = "SkyliveUsers"

   nome = attributes.text(allowNone=True, indexed=True)
   cognome = attributes.text(allowNone=True, indexed=True)
   telescopio = attributes.boolean(default=False)
   preferenza = attributes.text(allowNone=True)
   giudizio = attributes.text(allowNone=True)
   email = attributes.text(allowNone=False, indexed=True)
   citta = attributes.text(allowNone=True)
   nazione = attributes.text(allowNone=True)
   username = attributes.text(allowNone=False, indexed=True)
   password = attributes.text(allowNone=False, indexed=True)
   admin = attributes.boolean(default=False, indexed=True)
   lingua = attributes.text(default="it", indexed=True)
   tsiscrizione = attributes.timestamp(indexed=True)
   lastlogin = attributes.timestamp(indexed=True, allowNone=True)
   active = attributes.boolean(default=False, indexed=True)
   uniqueid = attributes.text(allowNone=False, indexed=True)
   hourtypes = attributes.textlist(allowNone=False, indexed=True, default=['default'])
   banned = attributes.boolean(indexed=True, default=False)
   mlist = attributes.boolean(indexed=True, default=True)
   privacycommercial = attributes.boolean(indexed=True, default=True)
   privacydefault = attributes.boolean(indexed=True, default=True)
   timezone = attributes.text(indexed=True, default='Europe/Rome')

   def updateLastLogin(self):
      self.lastlogin = extime.Time.fromPOSIXTimestamp(time.time())

   def updateUserDetails(self, password, nome, cognome, citta, email, mlist='yes'):
      self.nome = unicode(nome)
      self.cognome = unicode(cognome)
      self.citta = unicode(citta)
      self.password = unicode(password)
      self.email = unicode(email)
      if mlist=='yes':
         self.mlist=True
      else:
         self.mlist=False

class IUserSubscriptions(Interface):
   """ UserSubscriptions Interface """


class UserSubscriptions(item.Item):

   implements(IUserSubscriptions)
   schemaVersion = 2

   typeName = 'UserSubscriptions'
   username = attributes.text(allowNone=False, indexed=True)
   subname = attributes.text(allowNone=False, indexed=True)
   price = attributes.money(default=100)
   expiration = attributes.timestamp(indexed=True)
   expireadvised = attributes.boolean(default=False, indexed=True)


class ISubscriptionsType(Interface):
   """ SubscriptionsType Interface """

class SubscriptionsType(item.Item):

   implements(ISubscriptionsType)

   typeName = 'SubscriptionsType'
   name = attributes.text(allowNone=False, indexed=True)
   telescopes = attributes.textlist(allowNone=False)
   price = attributes.money(default=100)
   duration = attributes.integer(default=12)
   public = attributes.boolean(default=False, indexed=True)

class IBannedIP(Interface):
   """ BannedIP Interface """

class BannedIP(item.Item):

   implements(IBannedIP)

   typeName = 'BannedIP'

   address = attributes.text(allowNone=False, indexed=True)
   cause = attributes.text(default='Unknown cause')
   bannedby = attributes.text(indexed=True)
   bannedwhen = attributes.timestamp(indexed=True)

class IHoursPayement(Interface):
   """ HoursPayement Interface """

class HoursPayement(item.Item):

   implements(IHoursPayement)

   typeName = 'HoursPayement'

   username = attributes.text(indexed=True, allowNone=False)
   date = attributes.timestamp(indexed=True, allowNone=False)
   hourstype = attributes.text(indexed=True, allowNone=False)
   hours = attributes.integer(default=0)

class IUserHours(Interface):
   """ UserHours Interface """

class UserHours(item.Item):

   implements(IUserHours)

   typeName = 'UserHours'

   username = attributes.text(indexed=True, allowNone=False)
   hourstype = attributes.text(indexed=True, allowNone=False)
   hours = attributes.integer(default=0)

class IHoursTypes(Interface):
   """ HoursTypes Interface """

class HoursTypes(item.Item):

   implements(IHoursTypes)
   schemaVersion = 2

   typeName = 'HoursType'

   name = attributes.text(allowNone=False, indexed=True)
   telescopes = attributes.textlist(allowNone=False)
   price = attributes.money(default=100)
   candistribute = attributes.boolean(default=False)
   mounthlimit = attributes.integer(allowNone=True, default=None)
   minpack = attributes.integer(default=1)
   startlimit  = attributes.integer(allowNone=True, default=None)
   stoplimit = attributes.integer(allowNone=True, default=None)
   rechargeperc = attributes.integer(allowNone=False, default=50)

class IMontlyHours(Interface):
   """  MontlyHours Interface """

class MontlyHours(item.Item):

   implements(IMontlyHours)
   schemaVersion = 2


   typeName = 'MontlyHours'

   username = attributes.text(allowNone=False, indexed=True)
   howmany = attributes.integer(default=1)
   hourstype = attributes.text(indexed=True, allowNone=False)
   donemonth = attributes.integer(indexed=True, default=0)

class ITelescopeStatusData(Interface):
   """ TelescopeStatusData Interface  """

class TelescopeStatusData(item.Item):

   implements(ITelescopeStatusData)
   schemaVersion = 1
   
   typeName = "TelescopeStatusData"

   ts = attributes.timestamp(indexed=True, allowNone=False)
   telescope = attributes.text(allowNone=False, indexed=True)
   # GOOD / BAD
   status = attributes.text(allowNone=False, indexed=True)
   # reason:
   # CONN = connection with telescope down
   # WHEATER = bad Weather
   # DOME = dome closed
   # STATUSOFF = Telescope isn't active
   # MULTIPLE =  multiple reasons
   # SERVER = server down
   reason = attributes.text(allowNone=True, default=None, indexed=True)

class ITelescopeBooking(Interface):
   """ TelescopeBooking Interface """

class TelescopeBooking(item.Item):

   implements(ITelescopeBooking)
   schemaVersion = 3

   typeName = 'TelescopeBooking'

   telescope = attributes.text(allowNone=False, indexed=True)
   username = attributes.text(allowNone=False, indexed=True)
   allowedusers = attributes.textlist(allowNone=False, indexed=True)
   timestart = attributes.timestamp(indexed=True, allowNone=False)
   timestop = attributes.timestamp(indexed=True, allowNone=False)
   used = attributes.boolean(default=False, indexed=True)
   hourstype = attributes.text(indexed=True, allowNone=False)
   # Can be: NOTYET, GOING, OK, KO_[REASON].
   # REASON is why the hours is'nt valid used, and it is when
   # a hour can be recharged. Maybe we insert also the percentage?
   result = attributes.text(allowNone=False, indexed=True, default='NOTYET')
   good = attributes.integer(indexed=True, default=0)
   bad = attributes.integer(indexed=True, default=0)

   def setGoing():
      self.result = unicode('GOING')

   def setOk():
      self.result = unicode('OK')

   def setKo(reas):
      self.result =  unicode('KO')

   def setUsed():
      self.used = True

def upgradeUserSubscriptions1to2(oldsub):
   return oldsub.upgradeVersion('UserSubscriptions', 1, 2,
                                 username=oldsub.username,
                                 subname=oldsub.subname,
                                 price=oldsub.price,
                                 expiration=oldsub.expiration,
                                 expireadvised=False)

def upgradeMontlyHours1to2(oldmo):
   return oldmo.upgradeVersion('MontlyHours', 1, 2,
                                username = oldmo.username,
                                howmany = oldmo.howmany,
                                hourstype = oldmo.hourstype,
                                donemonth = 0)



def upgradeHoursTypes1to2(oldh):
   return oldh.upgradeVersion('HoursType', 1, 2,
                                name = oldh.name,
                                telescopes = oldh.telescopes,
                                price = oldh.price,
                                candistribute = oldh.candistribute,
                                mounthlimit = oldh.mounthlimit,
                                minpack = oldh.minpack,
                                startlimit = oldh.startlimit,
                                stoplimit = oldh.stoplimit,
                                rechargeperc = 50)


def upgradeTelescopeBooking1to2(oldtb):
   return oldtb.upgradeVersion('TelescopeBooking', 1, 2,
                                telescope = str(oldtb.telescope),
                                username = oldtb.username,
                                allowedusers = oldtb.allowedusers,
                                timestart = oldtb.timestart,
                                timestop = oldtb.timestop,
                                used = oldtb.used,
                                hourstype = oldtb.hourstype,
                                result = 'NOTYET')

def upgradeTelescopeBooking2to3(oldtb):
   return oldtb.upgradeVersion('TelescopeBooking', 1, 2,
                                telescope = str(oldtb.telescope),
                                username = oldtb.username,
                                allowedusers = oldtb.allowedusers,
                                timestart = oldtb.timestart,
                                timestop = oldtb.timestop,
                                used = oldtb.used,
                                hourstype = oldtb.hourstype,
                                result = oldtb.result,
                                good = 0,
                                bad = 0)


def upgradeSkyliveUsers1to2(oldu):
   return oldu.upgradeVersion('SkyliveUsers', 1, 2,
                               nome = oldu.nome,
                               cognome = oldu.cognome,
                               telescopio = oldu.telescopio,
                               preferenza = oldu.preferenza,
                               giudizio = oldu.giudizio,
                               email = oldu.email,
                               citta = oldu.citta,
                               nazione = oldu.nazione,
                               username = oldu.username,
                               password = oldu.password,
                               admin = oldu.admin,
                               lingua = oldu.lingua,
                               tsiscrizione = oldu.tsiscrizione,
                               lastlogin = oldu.lastlogin,
                               active = oldu.active,
                               uniqueid = oldu.uniqueid,
                               hourtypes = oldu.hourtypes,
                               banned = oldu.banned,
                               mlist = oldu.mlist,
                               privacycommercial = oldu.privacycommercial,
                               privacydefault = oldu.privacydefault,
                               timezone = unicode('+1'))


from axiom.upgrade import registerUpgrader
registerUpgrader(upgradeUserSubscriptions1to2, 'UserSubscriptions', 1, 2)
registerUpgrader(upgradeMontlyHours1to2, 'MontlyHours', 1, 2)
registerUpgrader(upgradeHoursTypes1to2, 'HoursType', 1, 2)
registerUpgrader(upgradeTelescopeBooking1to2, 'TelescopeBooking', 1, 2)
registerUpgrader(upgradeSkyliveUsers1to2, 'SkyliveUsers', 1, 2)
registerUpgrader(upgradeTelescopeBooking2to3, 'TelescopeBooking', 2, 3)

#print os.path.abspath(os.path.dirname(sys.argv[0]))+'/AxiomDB'
#SkyliveStore = store.Store(os.path.abspath(os.path.dirname(sys.argv[0]))+'/AxiomDB')
storepath = os.path.abspath(os.path.dirname(__file__)+'/../../AxiomDB')
pidfile=storepath+'/run/batch.pid'
print storepath
SkyliveStore = store.Store(storepath)

def get_pid():
   try:
      f = open(pidfile)
      pid = int(f.readline().strip())
      f.close()
   except IOError:
      pid = None
   return pid

