from ckan.lib.plugins import DefaultDatasetForm
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckan.lib.helpers import is_url, url_for
from . import helpers as collection_helpers
from flask import Blueprint

class CollectionsPlugin(plugins.SingletonPlugin, DefaultDatasetForm):
    plugins.implements(plugins.IDatasetForm, inherit=True)
    plugins.implements(plugins.ITemplateHelpers)
    plugins.implements(plugins.IBlueprint)


    # IDataSetForm
    def package_types(self):
        return ('collection', )
    
    def is_fallback(self):
        return False
    
    def read_template(self):
        return 'package/collection_read.html'

    
    # IBlueprint
    def get_blueprint(self):
        blueprint = Blueprint('odsh_collection', self.__module__)

        blueprint.add_url_rule('/collection/<id>/aktuell', 'latest_dataset', self.latest_dataset)
        blueprint.add_url_rule('/collection/<id>/aktuell.<resource_format>', 'latest_resource', self.latest_resource)
        return blueprint


    # ITemplateHelpers
    def get_helpers(self):
        # Template helper function names should begin with the name of the
        # extension they belong to, to avoid clashing with functions from
        # other extensions.

        return {
            'get_collection': collection_helpers.get_collection,
            'get_collection_info': collection_helpers.get_collection_info,
            'url_from_id': collection_helpers.url_from_id,
        }

    def latest_dataset(self, id):
        latest_dataset = collection_helpers.get_latest_dataset(id)
        if latest_dataset is None:
            toolkit.abort(404)
        return toolkit.redirect_to('dataset.read', id=latest_dataset)


    def latest_resource(self, id, resource_format):
        latest_resources = collection_helpers.get_latest_resources_for_format(id, resource_format)
        if latest_resources is None:
            toolkit.abort(404)
        url_type = latest_resources.get('url_type')
        if url_type is None:
            resource_url = latest_resources.get('url')
            return toolkit.redirect_to(resource_url)
        if url_type == 'upload':
            download_package_id = latest_resources.get('package_id')
            download_resource_id = latest_resources.get('id')
            pre_resource_url = latest_resources.get('url')
            if is_url(pre_resource_url):
                url_resource = pre_resource_url
            else:
                url_resource = url_for(named_route='dataset.resource_download',
                                       id=download_package_id,
                                       resource_id=download_resource_id,
                                       filename=pre_resource_url)
            return toolkit.redirect_to(url_resource)
        else:
            toolkit.abort(404)