# Path: opendiamond/scope.py
# def generate_cookie_django(scopeurls, servers, proxies=None, blaster=None):
#     '''A variant of generate_cookie() which pulls the more obscure fixed
#     arguments from Django settings.
# 
#     The signing key file comes from settings.SCOPE_KEY_FILE, if present.
# 
#     The expiration time (in seconds) comes from
#     settings.SCOPE_COOKIE_EXPIRATION, if present.'''
# 
#     from django.conf import settings
#     keyfile = getattr(settings, 'SCOPE_KEY_FILE', None)
#     expires = getattr(settings, 'SCOPE_COOKIE_EXPIRATION', None)
#     if expires is not None:
#         expires = timedelta(seconds=expires)
#     return generate_cookie(scopeurls, servers, proxies=proxies,
#                            keyfile=keyfile, expires=expires, blaster=blaster)
# 
# Path: opendiamond/scopeserver/mirage/forms.py
# class MirageForm(forms.Form):
#     def __init__(self, *args, **kwargs):
#         super(MirageForm, self).__init__(*args, **kwargs)
#         self.fields['servers'].choices = list(zip(settings.MIRAGE_SERVERS,
#                                              settings.MIRAGE_SERVERS))
# 
#     paths = forms.CharField(required=False, widget=forms.Textarea,
#                             label="Specify file name patterns (one per line)")
#     servers = forms.MultipleChoiceField(
#         choices=(), required=False, label="Select one or more compute servers")


from builtins import range
from django.contrib.auth.decorators import permission_required
from django.conf import settings
from django.http import QueryDict, HttpResponse
from django.shortcuts import render
from opendiamond.scope import generate_cookie_django
from .forms import MirageForm

@permission_required('mirage.search')
def index(request):
    if request.method == 'POST':
        form = MirageForm(request.POST)

        if form.is_valid():
            paths = form.cleaned_data.get('paths', '').split('\n')
            paths = [path.strip() for path in paths]  # trim whitespace
            paths = [path for path in paths if path]  # skip empty

            q = QueryDict('').copy()
            q.setlist('path', paths)
            query = q.urlencode()
            if query:
                query = "?" + query

            servers = form.cleaned_data['servers']

            cookie = []
            n = len(servers)
            for i in range(n):
                scope = ["%s/mirage/%dof%d%s" %
                         (settings.MIRAGE_DATARETRIEVER, i+1, n, query)]
                cookie.append(generate_cookie_django(
                    scope, (servers[i],),
                    blaster=getattr(settings, 'MIRAGE_BLASTER', None)))

            return HttpResponse(''.join(cookie), content_type='application/x-diamond-scope')
    else:

# Path: opendiamond/scope.py
# def generate_cookie_django(scopeurls, servers, proxies=None, blaster=None):
#     '''A variant of generate_cookie() which pulls the more obscure fixed
#     arguments from Django settings.
# 
#     The signing key file comes from settings.SCOPE_KEY_FILE, if present.
# 
#     The expiration time (in seconds) comes from
#     settings.SCOPE_COOKIE_EXPIRATION, if present.'''
# 
#     from django.conf import settings
#     keyfile = getattr(settings, 'SCOPE_KEY_FILE', None)
#     expires = getattr(settings, 'SCOPE_COOKIE_EXPIRATION', None)
#     if expires is not None:
#         expires = timedelta(seconds=expires)
#     return generate_cookie(scopeurls, servers, proxies=proxies,
#                            keyfile=keyfile, expires=expires, blaster=blaster)
# 
# Path: opendiamond/scopeserver/mirage/forms.py
# class MirageForm(forms.Form):
#     def __init__(self, *args, **kwargs):
#         super(MirageForm, self).__init__(*args, **kwargs)
#         self.fields['servers'].choices = list(zip(settings.MIRAGE_SERVERS,
#                                              settings.MIRAGE_SERVERS))
# 
#     paths = forms.CharField(required=False, widget=forms.Textarea,
#                             label="Specify file name patterns (one per line)")
#     servers = forms.MultipleChoiceField(
#         choices=(), required=False, label="Select one or more compute servers")


# Path: opendiamond/scopeserver/mirage/views.py
from builtins import range
from django.contrib.auth.decorators import permission_required
from django.conf import settings
from django.http import QueryDict, HttpResponse
from django.shortcuts import render
from opendiamond.scope import generate_cookie_django
from .forms import MirageForm


@permission_required('mirage.search')
def index(request):
    if request.method == 'POST':
        form = MirageForm(request.POST)

        if form.is_valid():
            paths = form.cleaned_data.get('paths', '').split('\n')
            paths = [path.strip() for path in paths]  # trim whitespace
            paths = [path for path in paths if path]  # skip empty

            q = QueryDict('').copy()
            q.setlist('path', paths)
            query = q.urlencode()
            if query:
                query = "?" + query

            servers = form.cleaned_data['servers']

            cookie = []
            n = len(servers)
            for i in range(n):
                scope = ["%s/mirage/%dof%d%s" %
                         (settings.MIRAGE_DATARETRIEVER, i+1, n, query)]
                cookie.append(generate_cookie_django(
                    scope, (servers[i],),
                    blaster=getattr(settings, 'MIRAGE_BLASTER', None)))

            return HttpResponse(''.join(cookie), content_type='application/x-diamond-scope')
    else:

        form = MirageForm()