from django.db import models
from ox.django.fields import DictField
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.forms import ValidationError
import re
import ox
from app.models import ItfModel
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
import urllib2
from decimal import Decimal

PANDORA_BASE = 'pad.ma'

class PadmaVideo(ItfModel):
#    embed_code = models.TextField()
#    url = models.CharField(max_length=512, editable=False)
    title = models.CharField(max_length=512, blank=True)
    poster = models.ImageField(blank=True, upload_to='upload/padmaposters/')
    padma_id = models.CharField(editable=False, max_length=16, unique=True, db_index=True)
    duration = models.DecimalField(max_digits=16, decimal_places=3, editable=False)
    width = models.IntegerField(null=True, editable=False)
    height = models.IntegerField(null=True, editable=False)
    data = DictField(default={}, editable=False)
    layers = DictField(default={}, editable=False)
    
    fts = ['title']

    def __unicode__(self):
        return self.padma_id
        
    def get_dict(self):
        return {
            #'embed_code': self.embed_code,
            #'url': self.url,
            'padma_id': self.padma_id,
            'duration': self.duration,
            'title': self.title,
            'data': self.data,
            #'time_in': self.time_in,
            #'time_out': self.time_out,
            'layers':self.layers,
            'clips': self.padmaclip_set.all()            
        }
    
    @property
    def padma_link(self):
        return "http://%s/%s" % (PANDORA_BASE, self.padma_id,)

    '''
    def save(self, *args, **kwargs):
        embed_code = self.embed_code
        regex = r'\<iframe width=\"([0-9]{1,3})\" height\=\"([0-9]{1,3})\" src\=\"http\:\/\/pad.ma\/([A-Z]{1,8})\/embed\?in\=([0-9].*?)\&out\=([0-9].*?)\&view\=video\" frameborder\=\"0\" allowfullscreen></iframe>'
        match = re.match(regex, embed_code)
        if not match:
            raise ValidationError("Invalid Embed Code")
        self.width, self.height, self.padma_id, self.time_in, self.time_out = match.groups()
        self.time_in = int(self.time_in)
        self.time_out = int(self.time_out)
        self.url = "http://%s/%s/" % (PANDORA_BASE, self.padma_id,) #FIXME time_in, time_out
        self.get_padma_data()
        super(PadmaVideo, self).save(*args, **kwargs)
    '''
    
    def get_padma_data(self, update_poster=True):
        api = ox.api.API("http://%s/api" % PANDORA_BASE)
        self.data = api.get({
            'id': self.padma_id,
            'keys': []
        })['data']
        if not self.title:
            self.title = self.data['title']
        self.duration = Decimal(str(self.data['duration']))
        if update_poster:
            self.update_poster()
        self.layers = api.get({
            'id': self.padma_id,
            'keys': ['layers']
        })
        return self
    
    #ref: http://djangosnippets.org/snippets/2587/
    def update_poster(self):
        #poster_time = int((self.time_in + self.time_out) / 2)
        poster_time = self.data['posterFrame']
        url = 'http://%s/%s/480p%d.jpg' % (PANDORA_BASE, self.padma_id, poster_time,)
        img_temp = NamedTemporaryFile(delete=True)
        img_temp.write(urllib2.urlopen(url).read())
        img_temp.flush()
        self.poster.save("%s.jpg" % self.padma_id, File(img_temp), save=False)


class PadmaClip(ItfModel):
    padmavideo = models.ForeignKey(PadmaVideo, editable=False)
    embed_code = models.TextField()
    time_in = models.DecimalField(max_digits=16, decimal_places=3, editable=False)
    time_out = models.DecimalField(max_digits=16, decimal_places=3, editable=False)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    
    @property
    def video_src(self, size=240):
        return "http://%s/%s/%dp.webm" % (PANDORA_BASE, self.padmavideo.padma_id, size)
    
    def save(self, *args, **kwargs):
        embed_code = self.embed_code
        regex = r'\<iframe width=\"([0-9]{1,3})\" height\=\"([0-9]{1,3})\" src\=\"http\:\/\/pad.ma\/([A-Z]{1,8})\/embed\?in\=([0-9\.].*?)\&out\=([0-9\.].*?)\&view\=video\" frameborder\=\"0\" allowfullscreen></iframe>'
        match = re.match(regex, embed_code)
        if not match:
            raise ValidationError("Invalid Embed Code")
        width, height, padma_id, time_in, time_out = match.groups()
        self.time_in = Decimal(time_in)
        self.time_out = Decimal(time_out)
        try:
            padmaVideo = PadmaVideo.objects.get(padma_id=padma_id)
            created = True
        except PadmaVideo.DoesNotExist:
            padmaVideo = PadmaVideo(padma_id=padma_id)
            created = False
        padmaVideo.get_padma_data(update_poster=created) #update poster only if video is freshly created
        padmaVideo.save()
        self.padmavideo = padmaVideo
        super(PadmaClip, self).save(*args, **kwargs)       
