# Path: ckanext/dcatapit/model/subtheme.py
# class Subtheme(DeclarativeBase, DomainObject):
#     __tablename__ = 'dcatapit_subtheme'
# 
#     id = Column(types.Integer, primary_key=True)
#     version = Column(types.Unicode, nullable=True)
#     identifier = Column(types.Unicode, nullable=False)
#     uri = Column(types.Unicode, nullable=False, unique=True)
#     default_label = Column(types.Unicode, nullable=False)
#     parent_id = Column(types.Integer, ForeignKey('dcatapit_subtheme.id'), nullable=True)
#     depth = Column(types.Integer, default=0)
#     path = Column(types.Unicode, nullable=False, unique=False)
#     themes = orm.relationship(Tag, secondary=ThemeToSubtheme.__table__)
#     parent = orm.relationship('Subtheme', lazy=True, uselist=False, remote_side=[id])
# 
#     @classmethod
#     def q(cls):
#         return cls.Session.query(cls)
# 
#     @classmethod
#     def get(cls, uri):
#         try:
#             return cls.q().filter_by(uri=uri).one()
#         except SAError:
#             return
# 
#     @classmethod
#     def get_any(cls, value):
#         q = cls.q()
#         try:
#             return q.filter(or_(cls.uri == value,
#                                 cls.identifier == value,
#                                 cls.default_label == value)).one()
#         except SAError:
#             return
# 
#     def get_names(self):
#         return [{'lang': n.lang, 'name': n.label} for n in self.names]
# 
#     def get_names_dict(self):
#         out = {}
#         for n in self.names:
#             out[n.lang] = n.label
#         return out
# 
#     def get_name(self, lang):
#         return self.get_names_dict()[lang]
# 
#     def get_path(self):
#         parent = self
#         old_parent = None
#         out = []
# 
#         while parent and parent != old_parent:
#             out.append(parent.default_label)
#             old_parent = parent
#             parent = parent.parent
#         return '/'.join(reversed(out))
# 
#     def update_path(self):
#         path = self.get_path()
#         self.path = path
# 
#     def __str__(self):
#         return 'Subtheme {} [{}] for {} themes'.format(
#             self.uri, self.default_label, ','.join([t.name for t in self.themes])
#         )
# 
#     @staticmethod
#     def normalize_theme(theme_uri):
#         return str(theme_uri).split('/')[-1]
# 
#     @classmethod
#     def for_theme(cls, theme, lang=None):
#         tag = ThemeToSubtheme.get_tag(theme)
#         if lang:
#             q = cls.Session.query(cls, SubthemeLabel.label)\
#                        .join(SubthemeLabel,
#                              and_(SubthemeLabel.subtheme_id == cls.id,
#                                   SubthemeLabel.lang == lang))\
#                        .join(ThemeToSubtheme,
#                              and_(ThemeToSubtheme.tag_id == tag.id,
#                                   ThemeToSubtheme.subtheme_id == cls.id))\
#                        .order_by(cls.parent_id, cls.path)
# 
#         else:
#             q = cls.Session.query(cls).join(ThemeToSubtheme,
#                                         and_(ThemeToSubtheme.tag_id == tag.id,
#                                              ThemeToSubtheme.subtheme_id == cls.id))\
#                 .order_by(cls.parent_id, cls.path)
#         return q
# 
#     @classmethod
#     def for_theme_values(cls, theme, lang=None):
#         q = cls.for_theme(theme, lang)
#         return [i.uri for i in q]
# 
#     @classmethod
#     def get_theme_names(cls):
#         q = cls.Session.query(Tag.name)\
#                    .join(ThemeToSubtheme,
#                          ThemeToSubtheme.tag_id == Tag.id)\
#                    .order_by(Tag.name)
#         return [t[0] for t in q]
# 
#     @classmethod
#     def get_localized(cls, *subthemes):
#         q = cls.Session.query(SubthemeLabel.lang, SubthemeLabel.label)\
#                    .join(cls, cls.id == SubthemeLabel.subtheme_id)\
#                    .filter(or_(cls.uri.in_(subthemes),
#                                cls.default_label.in_(subthemes)))
#         return q


import datetime
import json
import logging
import ckan.lib.helpers as h
import ckan.plugins.toolkit as toolkit
import ckanext.dcatapit.interfaces as interfaces
import ckanext.dcatapit.schema as dcatapit_schema
from ckan.lib.base import config
from ckan.model import GroupExtra, Session
from ckan.plugins import PluginImplementations
from ckanext.harvest.model import HarvestObject
from markupsafe import Markup
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from ckanext.dcatapit.model.subtheme import Subtheme
        if val:
            return [{'identifier': v} for v in val.split(',')]


def get_geonames_config():
    out = {}
    uname = config.get(GEONAMES_USERNAME)
    limit_to = config.get(GEONAMES_LIMIT_TO)
    if uname:
        out['username'] = uname
    if limit_to:
        out['limit_to'] = limit_to
    return out


def get_localized_subtheme(subtheme_id, lang):
    return interfaces.get_localized_subtheme(subtheme_id, lang) or subtheme_id


def get_dcatapit_subthemes(lang):
    """
    Dump subthemes tree with localized lables for all themes
    """
    out = {}

    def _get_name(opt_val, depth):
        return '{} {}'.format('-' * depth, opt_val)

    for theme in Subtheme.get_theme_names():
        out[theme] = theme_l = []

# Path: ckanext/dcatapit/model/subtheme.py
# class Subtheme(DeclarativeBase, DomainObject):
#     __tablename__ = 'dcatapit_subtheme'
# 
#     id = Column(types.Integer, primary_key=True)
#     version = Column(types.Unicode, nullable=True)
#     identifier = Column(types.Unicode, nullable=False)
#     uri = Column(types.Unicode, nullable=False, unique=True)
#     default_label = Column(types.Unicode, nullable=False)
#     parent_id = Column(types.Integer, ForeignKey('dcatapit_subtheme.id'), nullable=True)
#     depth = Column(types.Integer, default=0)
#     path = Column(types.Unicode, nullable=False, unique=False)
#     themes = orm.relationship(Tag, secondary=ThemeToSubtheme.__table__)
#     parent = orm.relationship('Subtheme', lazy=True, uselist=False, remote_side=[id])
# 
#     @classmethod
#     def q(cls):
#         return cls.Session.query(cls)
# 
#     @classmethod
#     def get(cls, uri):
#         try:
#             return cls.q().filter_by(uri=uri).one()
#         except SAError:
#             return
# 
#     @classmethod
#     def get_any(cls, value):
#         q = cls.q()
#         try:
#             return q.filter(or_(cls.uri == value,
#                                 cls.identifier == value,
#                                 cls.default_label == value)).one()
#         except SAError:
#             return
# 
#     def get_names(self):
#         return [{'lang': n.lang, 'name': n.label} for n in self.names]
# 
#     def get_names_dict(self):
#         out = {}
#         for n in self.names:
#             out[n.lang] = n.label
#         return out
# 
#     def get_name(self, lang):
#         return self.get_names_dict()[lang]
# 
#     def get_path(self):
#         parent = self
#         old_parent = None
#         out = []
# 
#         while parent and parent != old_parent:
#             out.append(parent.default_label)
#             old_parent = parent
#             parent = parent.parent
#         return '/'.join(reversed(out))
# 
#     def update_path(self):
#         path = self.get_path()
#         self.path = path
# 
#     def __str__(self):
#         return 'Subtheme {} [{}] for {} themes'.format(
#             self.uri, self.default_label, ','.join([t.name for t in self.themes])
#         )
# 
#     @staticmethod
#     def normalize_theme(theme_uri):
#         return str(theme_uri).split('/')[-1]
# 
#     @classmethod
#     def for_theme(cls, theme, lang=None):
#         tag = ThemeToSubtheme.get_tag(theme)
#         if lang:
#             q = cls.Session.query(cls, SubthemeLabel.label)\
#                        .join(SubthemeLabel,
#                              and_(SubthemeLabel.subtheme_id == cls.id,
#                                   SubthemeLabel.lang == lang))\
#                        .join(ThemeToSubtheme,
#                              and_(ThemeToSubtheme.tag_id == tag.id,
#                                   ThemeToSubtheme.subtheme_id == cls.id))\
#                        .order_by(cls.parent_id, cls.path)
# 
#         else:
#             q = cls.Session.query(cls).join(ThemeToSubtheme,
#                                         and_(ThemeToSubtheme.tag_id == tag.id,
#                                              ThemeToSubtheme.subtheme_id == cls.id))\
#                 .order_by(cls.parent_id, cls.path)
#         return q
# 
#     @classmethod
#     def for_theme_values(cls, theme, lang=None):
#         q = cls.for_theme(theme, lang)
#         return [i.uri for i in q]
# 
#     @classmethod
#     def get_theme_names(cls):
#         q = cls.Session.query(Tag.name)\
#                    .join(ThemeToSubtheme,
#                          ThemeToSubtheme.tag_id == Tag.id)\
#                    .order_by(Tag.name)
#         return [t[0] for t in q]
# 
#     @classmethod
#     def get_localized(cls, *subthemes):
#         q = cls.Session.query(SubthemeLabel.lang, SubthemeLabel.label)\
#                    .join(cls, cls.id == SubthemeLabel.subtheme_id)\
#                    .filter(or_(cls.uri.in_(subthemes),
#                                cls.default_label.in_(subthemes)))
#         return q


# Path: ckanext/dcatapit/helpers.py
import datetime
import json
import logging
import ckan.lib.helpers as h
import ckan.plugins.toolkit as toolkit
import ckanext.dcatapit.interfaces as interfaces
import ckanext.dcatapit.schema as dcatapit_schema
from ckan.lib.base import config
from ckan.model import GroupExtra, Session
from ckan.plugins import PluginImplementations
from ckanext.harvest.model import HarvestObject
from markupsafe import Markup
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from ckanext.dcatapit.model.subtheme import Subtheme

        if val:
            return [{'identifier': v} for v in val.split(',')]


def get_geonames_config():
    out = {}
    uname = config.get(GEONAMES_USERNAME)
    limit_to = config.get(GEONAMES_LIMIT_TO)
    if uname:
        out['username'] = uname
    if limit_to:
        out['limit_to'] = limit_to
    return out


def get_localized_subtheme(subtheme_id, lang):
    return interfaces.get_localized_subtheme(subtheme_id, lang) or subtheme_id


def get_dcatapit_subthemes(lang):
    """
    Dump subthemes tree with localized lables for all themes
    """
    out = {}

    def _get_name(opt_val, depth):
        return '{} {}'.format('-' * depth, opt_val)

    for theme in Subtheme.get_theme_names():
        out[theme] = theme_l = []

        for opt, label in Subtheme.for_theme(theme, lang):