from .base import ApiJob
from base64 import b64encode, b64decode
from common.models import Job
from common.util.clients import CacheClient
from common.util.decorators import api_token_required
from django.http import Http404, HttpResponse
import json


class JobConsole(ApiJob):
    http_method_names = ['get', 'post']

    @api_token_required
    def post(self, request, job):
        try:
            job = Job.check_job(Job.objects.get(n=job.id))
        except Job.Deleted:
            return HttpResponse(json.dumps([{'success': 0, 'msg': 'Job had been deleted'}]), content_type='application/json')
        except Job.DoesNotExist:
            raise Http404('Job not found')
        data = request.POST.get('console', '')
        data = b64encode(data)
        cache = CacheClient()
        success = cache.set('console_%s' % str(job.id), data)
        return HttpResponse(json.dumps([{'success': success}]), content_type='application/json')

    @api_token_required
    def get(self, request, job):
        try:
            job = Job.check_job(Job.objects.get(n=job.id))
        except Job.Deleted:
            return HttpResponse(json.dumps([{'success': 0, 'msg': 'Job had been deleted'}]), content_type='application/json')
        except Job.DoesNotExist:
            raise Http404('Job not found')
        cache = CacheClient()
        data = cache.get('console_%s' % str(job.id))
        if not data:
            data = ''
        data = b64decode(data)
        return HttpResponse(data, content_type='text/plain; charset=UTF-8')
