# from files.models import File
# from parse_drive import spider
from settings import UPLOAD_ROOT
import os, struct
from os.path import join

'''
def addFiles(cls, category, user, folder_name):
  path = join(UPLOAD_ROOT, folder_name)
#  spider(path, addFile, category=category)
  for dirpath, dirnames, filenames in os.walk(path):
    if filenames:
#            prefix = dirpath[len(path)+1:]
      for filename in filenames:
        if not filename.startswith('._') and not filename in ('.DS_Store', ):
          cls.add_from_path(category, user, join(dirpath, filename))
#                    print dirpath  + " + " + filename
                     

def addFile(dirpath, filename, opts):
  category = opts.category
  path = join(dirpath, filename)
  base_path = join(UPLOAD_ROOT, category.folder_name)
  relative_path = base_path.replace(UPLOAD_ROOT, "")
                        
  print dirpath + "'" + filename + "'"
'''
  
def getFileType(path, ext):
  if ext in ['ogv']:
    return 'video'
  elif ext in ['ogg']:
    return 'audio'
  elif ext in ['docx', 'doc', 'pdf', 'rtf', 'txt', 'html']:
    return 'text'
  elif ext in ['jpg', 'jpeg', 'png']:
    return 'image'
  else:
    return 'other'

#This function should return all info about a file which is to be stored in the DictField
def fileInfo(path):
  stat = os.stat(path)
  return {
    'size': stat.st_size,
    'mtime': stat.st_mtime,
    'atime': stat.st_atime,
    'ctime': stat.st_ctime,
  }

#From: http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes#Python
def hashFile(name): 
      try: 
                 
                longlongformat = 'q'  # long long 
                bytesize = struct.calcsize(longlongformat) 
                    
                f = open(name, "rb") 
                    
                filesize = os.path.getsize(name) 
                hash = filesize 
                    
                if filesize < 65536 * 2: 
                       return "SizeError" 
                 
                for x in range(65536/bytesize): 
                        buffer = f.read(bytesize) 
                        (l_value,)= struct.unpack(longlongformat, buffer)  
                        hash += l_value 
                        hash = hash & 0xFFFFFFFFFFFFFFFF #to remain as 64bit number  
                         
    
                f.seek(max(0,filesize-65536),0) 
                for x in range(65536/bytesize): 
                        buffer = f.read(bytesize) 
                        (l_value,)= struct.unpack(longlongformat, buffer)  
                        hash += l_value 
                        hash = hash & 0xFFFFFFFFFFFFFFFF 
                 
                f.close() 
                returnedhash =  "%016x" % hash 
                return returnedhash 
    
      except(IOError): 
                return "IOError"

