"""
Created on Mar 12, 2015

@author: noob
"""

from .base import ApiJob
from common.models import Artifact
from django.http import HttpResponseBadRequest, HttpResponse
from json import dumps, loads
import logging


class AddArtifact(ApiJob):
    http_method_names = ['post']

    @staticmethod
    def post(request, job):
        try:
            storage_key = loads(request.body).get('storage_key', '')
            assert storage_key
            Artifact.objects.create(
                job=job,
                storage_key=storage_key,
            )
            return HttpResponse(dumps([{'success': True}]), content_type='application/json')
        except AssertionError:
            return HttpResponseBadRequest()
        except Exception as exc:
            logging.exception("Could not add artifact for job {} due to:".format(job))
            return HttpResponse(dumps([{'success': False, 'error': exc.__class__.__name__}]),
                                content_type='application/json')
