from django.db import models
from tagging.fields import TagField
from tagging.models import Tag
from django.contrib.auth.models import User
import os
from convert import convertFile
from django.db.models.signals import post_save

def baseFileName(filename):
  r = filename.rindex('.')
  return filename[0:r]

def extFileName(filename):
  r = filename.rindex('.') + 1
  return filename[r:]


MIME_TYPES = (
    ('jpg', 'Image'),
    ('ogv', 'Video'),
    ('mp3', 'Audio'),
    ('txt', 'Text'),
    ('oth', 'Other'),
    ('hid', 'Hidden'),
)

class File(models.Model):
  file = models.FileField('File', upload_to='files')
  title = models.CharField(max_length=255)
  description = models.TextField(blank=True)
  tags = TagField("Tags", help_text="Enter as many tags as you like, separated by commas")
  userID = models.ForeignKey(User)
  file_date = models.DateField("Date", blank=True, null=True)
  added = models.DateField("Date Added", auto_now_add=True)
  categories = models.ManyToManyField('Category', verbose_name='Studies')
  type = models.ForeignKey('Type', verbose_name='File Type')

  def __unicode__(self):
    return self.title

  def original_print(self):
    basePath = "media/images/original/"
    filename = os.path.basename(str(self.file.url))
    if extFileName(filename).lower() != 'jpg':
      f = baseFileName(filename) + ".jpg"
    else:
      f = filename
    return basePath + f

class Category(models.Model):
  name = models.CharField(max_length=255)

  def __unicode__(self):
    return self.name

  class Meta:
    verbose_name = 'Study'
    verbose_name_plural = 'Studies'

class Type(models.Model):
  name = models.CharField(max_length=255)
  mime = models.CharField(choices=MIME_TYPES, verbose_name="Type of File", blank=True, null=True, max_length=20)  
#  mim = models.ChoiceField(choices=MIME_TYPES)  
  def __unicode__(self):
    return "%s - %s" % (self.name, self.mime)

  class Meta:
    verbose_name = 'File Type'
    verbose_name_plural = 'File Types'

post_save.connect(convertFile, sender=File)
