#!/usr/bin/env python
import os
from datetime import datetime
import time

# from math import fmod as fmod
PACK_NOT_INSTALLED= 0
PACK_INSTALLED=1
PACK_UPDATABLE=2


# import datetime
class Package(object):
  """ Class implementing information about package """

  def __init__ (self, dict={}):
    try:
      keys= self.dict.keys()
    except:
      self.dict={}
    for k,v in dict.iteritems():
      self.dict[k]= v
    if not self.dict.has_key('nfiles'):
      nf,files= self.__get_files()
      self.dict['nfiles']=nf
      if len(files[0]) > 0:
        self.dict['runfiles']=  files[0]
      if len(files[1]) > 0:
        self.dict['docfiles']=  files[1]
      if len(files[2]) > 0:
        self.dict['sourcefiles']=files[2]
      
  def get_property(self,prop):
    try:
      return self.dict[prop]
    except:
      return None

  def has_property(self,prop):
    return self.dict.has_key(prop)

  def set_property(self,prop, val):
    self.dict[prop]=val

  def remove_property(self,prop):
    if self.dict.has_key(prop):
      del self.dict[prop]
    
  def list_properties(self):
    k= self.dict.keys()
    k.sort()
    return k

  
  def print_files(self,tipo):
    tipos=[u'runfiles', u'docfiles', u'sourcefiles']
    s=u""
    if tipo not in tipos:
      return s
    files= self.get_property(tipo)
    for f in files:
      s += unicode(f).replace('texmf','').replace('\\','/') + '\n'
      
    return s
    


  def __get_files(self):
    tipos=['runfiles', 'docfiles', 'sourcefiles']
    nf=0
    ff=[]
    for t in tipos:
      files=[]
      if self.dict.has_key(t):
        files= self.get_property(t).split(' ')
        l=len(files)
        if l ==1:
          if files[0].strip()=="":
            l=0
        nf += l
      ff.append(files)
    return nf,ff


############################################################################
############################################################################
########             NO MORE USE OF INTERNAL STRUCTURE              ########
############################################################################
############################################################################
  def installed_state(self):
    if self.is_installed():
      if self.is_updatable():
        return PACK_UPDATABLE
      else:
        return PACK_INSTALLED
    return PACK_NOT_INSTALLED

  def is_installed(self):
    return (self.has_property('timeinstalled') and self.get_time_installed()!= None)

  def is_updatable(self):
    if self.is_installed():
#       print self.get_property('name'), self.get_property('timeinstalled'), self.get_time_installed()
#       print self.get_property('name'), self.get_property('timepackaged'), self.get_time_packaged()
      return (self.get_time_installed() < self.get_time_packaged())
    return False

  def get_time_packaged(self, full=False):
    ti= self.get_property('timepackaged')
    if ti and ti.strip() != '0':
      ti= datetime.fromtimestamp(float(ti))
      if not full:
        ti=ti.date()
      return ti
    else:
      return None
  def get_time_installed(self, full=False):
    ti= self.get_property('timeinstalled')
    if ti and ti.strip() != '0':
      ti= datetime.fromtimestamp(float(ti))
      if not full:
        ti=ti.date()
      return ti
    else:
      return None

  def set_time_installed(self, date=''):
    if date == 'now':
      ti= time.time()
      self.set_property('timeinstalled',ti)
    elif str(date).strip() == '':
      self.remove_property('timeinstalled')
    else:
      self.set_property('timeinstalled',date)


  def get_time_packaged(self, full=False):
    ti= self.get_property('timepackaged')
    if ti:
      ti= datetime.fromtimestamp(float(ti))
      if not full:
        ti=ti.date()
      return ti

#   def set_time_packaged(self, date=''):
#     if date == 'now':
#       ti= time.time()
#     else:
#       ti=""
#     self.set_property('timepackaged',ti)

  def get_values(self):
    """ Convenience function only used to fill the table of the GUI"""
    return (self, self.is_installed(), self.get_property('name'), self.get_property('nfiles'),
            self.get_property('size'),self.get_time_installed(), self.get_property('title'))


  def print_property(self,prop, separator=u' = '):
    s= self.get_property(prop)
    if s:
      s= prop  + separator + unicode(s)
    else:
      s= ""
    return s


  def print_values(self):
    """ Convenience function, used only for easy printing. """
    props= ['nfiles','size','name','title']

    if self.is_installed():
      val=('i',)
    else:
      val=('-',)
    for p in props:
      val += (self.get_property(p),)
    return val

  def print_info(self, verbose=False):
    """  """
    props= ['name','title','description']
    filetype= [u'docfiles']
    if verbose:
      props += ['nfiles','size']
      filetype.append(u'runfiles')
      filetype.append(u'sourcefiles')
    s=""
    for p in props:
      s += self.print_property(p, ': ') + '\n'
    s += '\n'

    for f in filetype:
      s += f+':\n'+ self.print_files(f) + '\n'
    s += '\n'
    return s


  def get_info(self):
    """Return a list of tuples of the form (prop,value)  """
    props= ['name','title','description','nfiles','size']
    filetype= ['runfiles','docfiles','sourcefiles']

    s=[]
    for p in props:
      s.append((p, self.get_property(p)))
    for f in filetype:
      s.append((f,self.print_files(f) + '\n'))

    return s


def test():
  p={}
  p['name']='accfonts'
  p['runfiles']='abst.sty ad//adsf//q12many.sty abstract.sty'
  p['docfiles']='ad//adsf//q12many.pdf abstract.pdf'
#   p['sourcefiles']='source.cab source.tar.gz'
  p['title']='dummy'
  p['description']='None'
  pack= Package(p)

  print pack.get_values(), 3*'\n'

  print pack.get_property('name'), 3*'\n'
  pack.set_property('name','Juan')
  print pack.get_property('name'), 3*'\n'
  print pack.list_properties(), 3*'\n'
  print pack.get_values(), 3*'\n'
  print pack.is_installed(), 3*'\n'
  print pack.get_info(verbose=True)
  pack.install()
  print pack.get_info(verbose=True)
  print pack.print_property('timeinstalled'), 3*'\n'

if __name__ == "__main__":
  test()
### Local Variables: 
### tab-width: 2
### END:
