import logging

from .tank import TankAPICommunicator, TankAPIError
from common.models import Job, Config
from django.http import HttpResponse, HttpResponseBadRequest
from mimetypes import MimeTypes


logger = logging.getLogger(__name__)


def get_artifact(request, job_id, filename):
    try:
        job_id = int(job_id)
        tank_api = TankAPICommunicator(job_id)
        file_data = tank_api.get_artifact(filename)
        file_type, _ = MimeTypes().guess_type(filename)
        return HttpResponse(file_data, content_type=file_type)
    except TankAPIError as e:
        return HttpResponseBadRequest(repr(e))


def get_config(request, job_id, filename):
    try:
        job_id = int(job_id)
        config = Config.objects.get(job_id=job_id, name=filename)
        file_type = MimeTypes().guess_type(config.name)
        return HttpResponse(config.content, content_type=file_type)
    except (Job.DoesNotExist, Config.DoesNotExist, ValueError) as e:
        return HttpResponseBadRequest(repr(e))
