#!/usr/bin/env python2.5
from zope.interface import Interface, implements
from axiom import item, attributes, store
from pysqlite2 import dbapi2
from epsilon import extime
import time
import md5

con =  dbapi2.connect("skylive.db")
cur = con.cursor()
cur.execute("SELECT * FROM Users")
rows = cur.fetchall()


# costo orario e ore utente


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

class SkyliveUsers(item.Item):
   
   implements(ISkyliveUsers)

   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)

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


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

class UserSubscriptions(item.Item):

   implements(IUserSubscriptions)

   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)


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)

   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)

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

class MontlyHours(item.Item):
   
   implements(IMontlyHours)

   typeName = 'MontlyHours'

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

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

class TelescopeBooking(item.Item):

   implements(ITelescopeBooking)

   typeName = 'TelescopeBooking'

   telescope = attributes.integer(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)


s = store.Store('../AxiomDB')

SubscriptionsType(store=s, name=u'FULL', telescopes=['1','2','4','5','6'], price=150, duration=12, public=True)
SubscriptionsType(store=s, name=u'Pedara', telescopes=['1','2','4'], price=100, duration=12, public=True)
SubscriptionsType(store=s, name=u'TRE', telescopes=['3'], price=0, duration=1200, public=False)
SubscriptionsType(store=s, name=u'GCO', telescopes=['5','6'], price=50, duration=12, public=False)
SubscriptionsType(store=s, name=u'SoloOre', telescopes=[], price=0, duration=None, public=False)
SubscriptionsType(store=s, name=u'ADMIN', telescopes=['1','2','3','4','5','6',], price=0, duration=1200, public=False)


HoursTypes(store=s, name=u'default', telescopes=['1','2','3','4','5','6'], price=7, candistribute=False)

for row in rows:
   tele=False
   adm=False
   if row[3] == 'SI': tele=True
   if row[12] == 'si': adm=True
   strm = unicode(unicode(row[0])+unicode(row[1])+unicode(row[2])+unicode(row[5])).encode('utf-8')
   m = md5.new(strm)
   uid = m.hexdigest()
   try:
      iscr = extime.Time.fromPOSIXTimestamp(time.mktime(time.strptime(row[17], "%m/%d/%y %H:%M:%S")))
   except:
      iscr = extime.Time.fromPOSIXTimestamp(time.time())
   SkyliveUsers(store=s, nome=row[0], cognome=row[1], giudizio=row[2], telescopio=tele,
                preferenza=row[4], email=row[5], citta=row[6], username=row[7], password=row[8],
                admin=adm, lingua=row[13], active=True, uniqueid=unicode(uid), tsiscrizione=iscr)
   if adm:
      UserSubscriptions(store=s, username=row[7], price=int(row[10]), expiration=None, subname=u'ADMIN')
   else:
      try:
         ped = row[9].replace(" ", "")
      except:
         ped = ""

      try:
         gco = row[11].replace(" ", "")
      except:
         gco = ""

      if len(ped) > 0:
         if str(row[9]).split("/")[2].split()[0] == '00':
            UserSubscriptions(store=s, username=row[7], price=int(0), expiration=None, subname=u'ADMIN')
         else:
            antani = row[9]
            #exp = datetime.datetime(*time.strptime(row[9], "%m/%d/%y %H:%M:%S")[0:6])
            exp = extime.Time.fromPOSIXTimestamp(time.mktime(time.strptime(antani, "%m/%d/%y %H:%M:%S"))+31536000)
            now = extime.Time.fromPOSIXTimestamp(time.time())
            old=int(exp.asPOSIXTimestamp())
            new=int(now.asPOSIXTimestamp())
            if exp == 0:
               exp=None
            pr=0
            if row[10]:
               pr = int(row[10])
            if old  >= new:
               UserSubscriptions(store=s, username=row[7], price=pr, expiration=exp, subname=u'Pedara')

      if len(gco) > 0:
         if not str(row[11]).split("/")[2].split()[0] == '00':
            antani = row[11]
            exp = extime.Time.fromPOSIXTimestamp(time.mktime(time.strptime(antani, "%m/%d/%y %H:%M:%S"))+31536000)
            now = extime.Time.fromPOSIXTimestamp(time.time())
            old=int(exp.asPOSIXTimestamp())
            new=int(now.asPOSIXTimestamp())
            if old  >= new:
               UserSubscriptions(store=s, username=row[7], price=50, expiration=exp, subname=u'GCO')
"""
(u'alberto ', u'Bulba', u'OTTIMO', u'SI', u'tante cose...', u'...', u'Trento', u'pupo', u'922542', None, None, None, None, u'italiano', u'19.13.44', None, None, u'12/18/07 00:00:00', None, None)

        Nome                    Text (40),
        Cognome                 Text (100),
        Giudizio                        Text (100),
        Telescopio                      Text (100),
        Oggetto                 Text (100),
        Email                   Text (100),
        Citta                   Text (100),
        Username                        Text (100),
        Password                        Text (100),
        Pagato                  DateTime (Short),
        Quota                   Long Integer,
        tele5                   DateTime (Short),
        Admin                   Text (100),
        Lingua                  Text (100),
        Ora                     Text (100),
        Live                    Text (100),
        Campo1                  Text (100),
        Data                    DateTime (Short),
        Last                    Text (24),
        Datatrial                       DateTime (Short)
"""
