"""
Created on Jul 3, 2013

@author: noob
"""

from .base import ApiJob
from common.models import Ammo, Job
from datetime import datetime
from django.http import HttpResponse, HttpResponseBadRequest
import json
import logging
from django_yauth.decorators import yalogin_required


def update_ammo_lastused(parsed_config):
    try:
        path = parsed_config.get('phantom', {}).get('ammofile')
        assert path
        ammo = Ammo.objects.filter(path=path)
        now = datetime.now()
        for a in ammo:
            a.last_used = now
            a.save()
    except AssertionError:
        pass
    except:
        logging.exception('')
        pass
    

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

    @staticmethod
    def get(request, job):
        """

        :param request: HTTP request
        :param job: Job OBJECT
        """
        try:
            configinfo = job.configinfo
        except:
            configinfo = ''
            logging.exception("Could not get configinfo for job {} due to:".format(job.n))
        return HttpResponse(configinfo, content_type='text/plain; charset=UTF-8')

    @staticmethod
    def post(request, job, **kwargs):
        """

        :param request: HTTP request
        :param job: Job OBJECT
        """
        try:
            configinfo = request.POST.__getitem__('configinfo')
        except KeyError:
            error = 'No "configinfo" parameter passed in post request for job {}'.format(job.n)
            logging.error(error)
            return HttpResponse(json.dumps([{'success': 0, 'error': error}]), content_type='application/json')
        except Exception as exc:
            logging.exception('Could not retrieve "configinfo" parameter from post request for job {} due to:'
                              .format(job.n))
            return HttpResponse(json.dumps([{'success': 0, 'error': repr(exc)}]),
                                content_type='application/json')
        try:
            job.configinfo = configinfo
            job.save()
            update_ammo_lastused(job.config)
            return HttpResponse(json.dumps([{'success': 1}]), content_type='application/json')
        except Exception as exc:
            logging.exception("Could not set configinfo for job {} due to:".format(job.n))
            return HttpResponse(json.dumps([{'success': 0, 'error': repr(exc)}]),
                                content_type='application/json')


@yalogin_required
def job_configinfo(request):
    """
    frontend handler
    :param request:HTTP request
    """
    job_n = request.GET.get('job_n')
    try:
        assert job_n
    except AssertionError:
        return HttpResponseBadRequest('job_n required')
    job = Job.objects.get(n=job_n)
    try:
        assert request.user == job.user
        configinfo = job.configinfo
    except AssertionError:
        configinfo = ''
        logging.error('Wrong job owner')
    except:
        configinfo = ''
        logging.exception('Could not get configinfo for job {} due to:'.format(job.n))
    return HttpResponse(configinfo, content_type='text/plain; charset=UTF-8')
