import os

from django.db import models
from django.contrib import admin
import uuid
import photologue.models
from django.conf import settings
from modeltranslation.utils import build_localized_fieldname
from modeltranslation.translator import translator
import tagging


def get_sid():
    return unicode(uuid.uuid1())

class Ioi(models.Model):
    
    class Meta:
        abstract = True
    
    sid = models.CharField(max_length=36, unique=True, blank=False, null=False, db_index=True, editable=False, default=get_sid)
    loc = models.CharField(max_length=512, unique=False, blank=True, null=True)
    loc_radius = models.FloatField(null=True, blank=True)
    title = models.CharField(max_length=1024, unique=True, blank=False, null=False)
    short_title = models.CharField(max_length=512, unique=True, blank=False, null=False)
    description = models.TextField(blank=True, null=True)
    
    photos = models.ForeignKey(photologue.models.Gallery, null=True)
    
    def serialize_to_dict(self):
        res = {
            "sid": self.sid,
        }
        
        # serialize translated fields
        trans_options = None
        try:
            trans_options = translator.get_options_for_model(self.__class__) 
        except:
            trans_options = None 
        if trans_options:
            for fieldname in trans_options.localized_fieldnames:
                lang_dict = {}
                for l in settings.LANGUAGES:
                    lang = l[0]
                    lfieldname = build_localized_fieldname(fieldname, lang)
                    lang_dict[lang] = self.__dict__[lfieldname]
                res[fieldname] = lang_dict
                
        res["loc"] = {}
        if self.loc:
            loc_array = self.loc.split(",")
            res["loc"] = { "type" : "Point", "coordinates": [float(loc_array[0]),float(loc_array[1])] }
        
        res["loc_radius"] = self.loc_radius
        
        res["photos"] = []
        
        if self.photos:
            for photo in self.photos.photos.all():
                res["photos"].append({"title":photo.title,"url":settings.WEB_URL.strip("/")+photo.image.url})

        return res

    

class Roi(Ioi):
        
    def __unicode__(self):
        return "%s : %s" % (unicode(self.pk),unicode(self.title))
        
    
class Poi(Ioi):

    roi = models.ForeignKey(Roi, null=False, related_name="region")
    base_tag = models.CharField(max_length=512, unique=True, blank=False, null=False, db_index=True)
    tags = tagging.fields.TagField(max_length=2048, blank=True, null=True)
    
    def serialize_to_dict(self):
        res = super(Poi, self).serialize_to_dict()
        res["roi"] = self.roi.sid
        res["base_tag"] = self.base_tag
        res["tags"] = self.tags
        return res

    def __unicode__(self):
        return "%s : %s" % (unicode(self.pk),unicode(self.title))



admin.site.register(Roi)
admin.site.register(Poi)
#tagging.register(Poi)

