from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseBadRequest
from griffin.models.download import ResumeDownload, DownloadFormat
from griffin.models.entity import Applicant
from griffin.models.resume import Resume
from griffin.resume_download import save_to_media

import logging
logger = logging.getLogger(__name__)

try:
    import pypandoc
    pypandoc.get_pandoc_formats()
    PANDOC_AVAILABLE=True
except OSError as e:
    logger.warn(e)
    PANDOC_AVAILABLE=False

def settings_pop(prop, alt_value):
    import django
    django.setup()
    from django.conf import settings
    logger.debug("Getting '%s' from settings..."%prop)
    if hasattr(settings, prop):
        p = getattr(settings, prop)
        logger.debug("Found! Returning '%s'"%p)
        return p
    logger.debug("Not found...returning '%s'"%alt_value)
    return alt_value

RESUME_ALL_TEMPLATE = settings_pop('RESUME_ALL_TEMPLATE', 'resume/all.html')
RESUME_TEMPLATE = settings_pop('RESUME_TEMPLATE', 'resume/resume.html')

def all(request, applicant_id):
    context = {
        'applicant' : Applicant.objects.get(pk=applicant_id),
        'resumes' : Resume.objects.filter(applicant__pk=applicant_id),
    }
    return render(request, RESUME_ALL_TEMPLATE, context)

def resume(request, applicant_id, resume_id):
    context = {
        'applicant' : Applicant.objects.get(pk=applicant_id),
        'resume' : Resume.objects.get(pk=resume_id)
    }
    return render(request, RESUME_TEMPLATE, context)

def download(request, resume_id, extension):
    
    resume = Resume.objects.get(pk=resume_id)
    context = {
        'resume' : resume,
        'applicant' : resume.applicant,
    }
    
    
    try:
        format = DownloadFormat.objects.get(extension=extension)
        res_dl = ResumeDownload.objects.get(resume=resume, format=format)
        logger.debug("Got %s in format %s"%(res_dl, format))
        
        if not res_dl.use_autogenerated_file and res_dl.media_link:
            media_link = res_dl.resume_file.url
            logger.debug("Returning %s"%media_link)
            return redirect(media_link)
        
        media_link = save_to_media(request,
                                    "resume/download.rst",
                                    context,
                                    extension)
        return redirect(media_link)
        
    except ObjectDoesNotExist as e:
        try:
            media_link = save_to_media(request,
                                        "resume/download.rst",
                                        context,
                                        extension)
        except ImportError as e:
            return  HttpResponseBadRequest(None)
    
    return redirect(media_link)