# -*- coding: utf-8 -*-

from jsmin import jsmin
import os
import cStringIO as StringIO

def slugs():
    """ Returns catalog.table for each table that has a geometry column """
    for dbname, odb in odbs.iteritems():
        for row in odb(odb.geometry_columns.srid>=0).select(
            odb.geometry_columns.table_catalog, odb.geometry_columns.table_name
        ):
            yield "{table_catalog}.{table_name}".format(**row)

db.define_table("mapfile",
    Field("slug", required=True, requires=IS_IN_SET(slugs(), zero=None)),
    # Eventualmente potrebbe essere testo libero
    Field("layer_type", requires=IS_IN_SET(["wms", "wfs"])),
    Field("mapfile", "upload", writable=False, readable=False, autodelete=True),
    Field("body", "text", required=True),
#     Field("template", "upload", rname='""', required=True),
    Field("opts", "json")
)

class mapfileCallbacks(object):

    @staticmethod
    def onInsert(f):
        stream = StringIO.StringIO(f["body"])
        filename = "%(slug)s_%(layer_type)s.map" % f
        f["mapfile"] = db.mapfile.mapfile.store(stream, filename)

    @staticmethod
    def onUpdate(s, f):
        for row in s.select():
            with open(os.path.join(os.getcwd(), request.folder, "uploads", row.mapfile), "wb") as mapfile:
                mapfile.write(f["body"])

    @classmethod
    def setup(cls):
        db.mapfile._before_insert.append(cls.onInsert)
        db.mapfile._after_update.append(cls.onUpdate)

mapfileCallbacks.setup()