# from files.models import *
#UGLY HACK trying to avoid circular import issue. Try n clean up.
import editor as e
from settings import MEDIA_ROOT
import os

def toJpg(f):
  fname = str(f.file)
  ext = e.models.extFileName(fname)
  output_path = "%s/media/images/original/%s" % (MEDIA_ROOT, e.models.baseFileName(os.path.basename(f.file.path)) + ".jpg",)
  if ext.lower() == 'jpg' or ext.lower() == 'jpeg':
#    print ext.lower()
    cmd = "cp '%s' '%s'" % (f.file.path, output_path,)
    os.system(cmd)
#    print cmd
  return

def toOgg(f):
  if f.ext == 'ogg':
    return
  output_path = "%s/media/audio/%s" % (MEDIA_ROOT, e.models.baseFileName(os.path.basename(f.file.path)) + ".ogg",)
  cmd = "ffmpeg2theora -o '%s' --no-skeleton --novideo '%s'" % (output_path, f.file.path,)
  os.system(cmd)
  a = e.models.Audio(fil=f)
  a.save()
  return

def toTxt(f):
  return
#  print f.file

def toOgv(f):
  if f.ext == 'ogv':
    return
  output_path = "%s/media/video/%s" % (MEDIA_ROOT, e.models.baseFileName(os.path.basename(f.file.path)) + ".ogv",)
  if e.models.extFileName(str(f.file)).lower() == 'ogv' or e.models.extFileName(str(f.file)).lower() == 'ogg':
    cmd = "cp %s %s" % (f.file.path, output_path)
  else:
    cmd = "ffmpeg2theora -p padma -o '%s' '%s'" % (output_path, f.file.path,)
  os.system(cmd)
  v = e.models.Video(fil=f)
  v.save()
  return

def ignoreFile(f):
  pass

#This function is called from the post_save signal, receives kwargs['instance'] as a File instance
def convertFile(**kwargs):
  f = kwargs['instance']
  if not f.done:
    return
  if f.type == '':
    if f.ext == '':
      fname = str(f.file)
      ext = e.models.extFileName(fname)
      f.ext = ext
    if f.ext.lower() in ['jpg', 'jpeg', 'png']:
      f.type = 'image'
    elif f.ext.lower() in ['ogg', 'oga']:
      f.type = 'audio'
    elif f.ext.lower() in ['ogv']:
      f.type = 'video'
    elif f.ext.lower() in ['doc', 'pdf', 'rtf', 'txt']:
      f.type = 'text'
    else:
      f.type = 'other'
    f.save()
  if str(f.file).startswith(MEDIA_ROOT):
    f.file = str(f.file).replace(MEDIA_ROOT, "")[1:]
    f.save()
  fn = {
    'image': ignoreFile,
    'audio': toOgg,
    'text': ignoreFile,
    'video': toOgv,
    'other': ignoreFile,
#    'other': ignoreFile
    }
  fn[f.type](f)
  return


def convertAll():
#Again - ugliness hacking at circular import silliness - clean up.
  import files
  for f in files.models.File.objects.all():
    convertFile(instance=f)
  return

