from __future__ import unicode_literals

import json

from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse

from ..core.utils import build_absolute_uri
from ..product.models import Category


def get_setting_as_dict(name, short_name=None):
    short_name = short_name or name
    try:
        return {short_name: getattr(settings, name)}
    except AttributeError:
        return {}


# request is a required parameter
# pylint: disable=W0613
def default_currency(request):
    return get_setting_as_dict('DEFAULT_CURRENCY')


# request is a required parameter
# pylint: disable=W0613
def categories(request):
    return {'categories': Category.tree.root_nodes().filter(is_hidden=False)}


def search_enabled(request):
    return {'SEARCH_IS_ENABLED': settings.ENABLE_SEARCH}


def webpage_schema(request):
    site = get_current_site(request)
    url = build_absolute_uri(location='/')
    data = {
        '@context': 'http://schema.org',
        '@type': 'WebSite',
        'url': url,
        'name': site.name,
        'description': site.settings.description}
    if settings.ENABLE_SEARCH:
        data['potentialAction'] = {
            '@type': 'SearchAction',
            'target': '%s%s?q={search_term}' % (url, reverse('search:search')),
            'query-input': 'required name=search_term'}
    return {'webpage_schema': json.dumps(data)}

@@ -256,16 +256,112 @@
 tegory%0A%0A
+try:%0A    from urllib.parse import urljoin%0Aexcept ImportError:%0A    from urlparse import urljoin%0A%0A
 %0Adef get
@@ -1258,16 +1258,76 @@
 SEARCH:%0A
+        search_url = urljoin(url, reverse('search:search'))%0A
         
@@ -1416,18 +1416,16 @@
 et': '%25s
-%25s
 ?q=%7Bsear
@@ -1440,39 +1440,18 @@
 ' %25 
-(url, reverse('search:search'))
+search_url
 ,%0A  

Fix search URL in Schema markup