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

"""
211111 The strategy was to log requests and to serve the binaries from
the server. Wavemetrics has changed their licensing structure, so that
licenses now expire. I don't think that there is any further need to
maintain records. Therefore, once a person has successfully been identified
as a legitimate HMC member, they are sent an email message with all the 
necessary information to download and install.
"""

from django.shortcuts import render, redirect
from django.template import RequestContext
from django.utils import timezone
from igor.models import Download
from django.http import StreamingHttpResponse, HttpResponse, Http404


def short_intro(request): return render(request, 'igor/short.html')
def long_intro(request): return render(request, 'igor/long.html')
def videos(request): return render(request, 'igor/screencasts.html')
def faq(request): return render(request, 'igor/faq.html')
def fitting(request): return render(request, 'igor/fitting.html')
def power_law(request): return render(request, 'igor/power.html')
def propagation(request): return render(request, 'igor/propagation.html')
def statistics(request): return render(request, 'igor/statistics.html')
def spreadsheets(request): return render(request, 'igor/spreadsheets.html')
def menu(request): return render(request, 'igor/HMCproc.html')
def hmcmenu(request): return render(request, 'igor/hmc_menu.html')


def main(request, **kwargs):
    return render(request, 'igor/igor.html', kwargs)


def download(request):
    if request.method != 'POST':
        return redirect('igor')
    name = request.POST['name']
    from people.identifier import identify_person
    pi = identify_person(name)
    if not pi():
        # return redirect('igor', error=f'I did not recognize {name}')
        return main(request, error="I did not recognize ‘{0}’".format(name))
    # Okay, now we have a valid person in the database. But, is this person legit?
    peep = pi.person
    legit = False
    if peep.is_x() == 'faculty':
        legit = True
    elif peep.is_x() == 'student':
        legit = peep.subclass().is_active()
    if not legit:
        return main(request, error="{0} is not a valid user".format(name))

    d = Download.objects.create(person=peep)
    d.send()
    # return send_download_info(request, d) 211111 replaced
    return render(request, 'igor/check_email.html', {'email': peep.email})


def send_download_info(request, download):
    c = RequestContext(request)
    return render(request, 'igor/send_download_info.html', {'download': download
                                                            })


def do_download(request):
    if request.method != 'POST':
        return main(request)
    try:
        key = request.POST['key']
        downloads = Download.objects.filter(key=key)
        if downloads.count() == 0:
            return main(request, error='Entered key was incorrect.')
        the_download = downloads[0]
        if the_download.retrieved:
            return main(request, **{'error': "That key has already been used."})
        the_download.retrieved = timezone.now()
        the_download.save()
        version = request.POST['version']
        if version.startswith('mac'):
            filename = f'Igor{version[3]}.dmg'
        else:
            filename = f'setupIgor{version[3]}.exe'
        return xsendfile(request, '/var/private/docs/igor/{0}'.format(filename))
    except Exception as eeps:
        return main(request, error=f'Encountered error {eeps}. Please try again.')
    return main(request)


def xsendfile(request, path):
    """
        This is a fake version of xsendfile that actually serves the file from
        within Django. Note that the directories up the line must be executable for
        www-data and that the file itself must be visible to www-data.
    """
    print(("xsendfile for {0}".format(path)))
    import mimetypes
    import os
    from django.conf import settings
    contentType = mimetypes.guess_type(path)[0]
    if settings.DEBUG:
        from wsgiref.util import FileWrapper
        wrapper = FileWrapper(open(path, "rb"))
        if contentType == "image/jpeg":
            response = StreamingHttpResponse(
                wrapper, content_type=contentType)
        else:
            response = StreamingHttpResponse(
                wrapper, content_type="application/force-download")
            response['Content-Disposition'] = "attachment; filename=" + \
                os.path.basename(path)
        response['Content-Length'] = os.path.getsize(path)
        return response

    try:
        response = HttpResponse(content_type=contentType)
        response['Content-Type'] = ''
        import urllib.parse
        u = urllib.parse.quote(path.encode('utf-8'))
        # print( u )
        response['X-Sendfile'] = u
        response['Content-Disposition'] = "attachment; filename=" + \
            os.path.basename(path)
        # print( "I'm referring to '%s'" % (response['X-Sendfile']))
    except:
        raise Http404
    return response
