"""
Created on Nov 21, 2016

@author: noob
"""

from .base import ApiJob
from common.models import JobEvent
from datetime import datetime
from django.http import HttpResponse, HttpResponseBadRequest
from json import dumps
import logging
import time


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

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

        :param request: HTTP request
        :param job: Job OBJECT
        """
        try:
            tag = request.GET.get('tag')
            author = request.GET.get('author')
            timestamp = request.GET.get('timestamp')
            _from = request.GET.get('from')
            _to = request.GET.get('to')

            events = JobEvent.objects.filter(job=job)
            if tag is not None:
                tags = tag.split('|') + [tag]
                events = events.filter(tag__in=tags)
            if author is not None:
                events = events.filter(author=author)
            if timestamp is not None and timestamp.isdigit():
                timestamp = datetime.fromtimestamp(int(timestamp))
                events = events.filter(timestamp=timestamp)
            if _from is not None and _from.isdigit():
                _from = datetime.fromtimestamp(int(_from))
                events = events.filter(timestamp__gte=_from)
            if _to is not None and _to.isdigit():
                _to = datetime.fromtimestamp(int(_to))
                events = events.filter(timestamp__lte=_to)

            events = [{'timestamp': int(time.mktime(e.timestamp.timetuple())),
                       'text': e.text,
                       'author': e.author,
                       'tag': e.tag,
                       } for e in events]
        except:
            logging.exception('')
            events = []
        return HttpResponse(dumps(events), content_type='application/json')

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

        :param request: HTTP request
        :param job: Job OBJECT
        """
        try:
            author = request.POST.get('author', '')
            text = request.POST.get('text', '')
            tag = request.POST.get('tag', '')
            timestamp = request.POST.get('timestamp', datetime.now())

            if not isinstance(timestamp, datetime) and timestamp.isdigit():
                timestamp = datetime.fromtimestamp(int(timestamp))
            else:
                return HttpResponseBadRequest(dumps([{'success': 0, 'error': 'invalid timestamp'}]),
                                              content_type='application/json')
            JobEvent.objects.create(
                author=author,
                text=text,
                timestamp=timestamp,
                job=job,
                tag=tag,
            )
            return HttpResponse(dumps([{'success': 1}]), content_type='application/json')
        except Exception as exc:
            logging.exception('Could not set event for job {} due to:'.format(job.n))
            return HttpResponse(dumps([{'success': 0, 'error': exc.__class__.__name__}]),
                                content_type='application/json')
