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

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

class Roi(models.Model):
    
    sid = models.CharField(max_length=36, unique=True, blank=False, null=False, db_index=True, editable=False, default=get_sid)
    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)
    loc = models.CharField(max_length=512, unique=False, blank=True, null=True)
    loc_radius = models.FloatField(null=True)
    photos = models.ForeignKey(photologue.models.Gallery, null=True)
    
    
    def serialize_to_dict(self):
        res = {
            "sid": self.sid,
        }
        
        for fieldname in ["title","short_title","description"]:
            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

admin.site.register(Roi) 