# -*- coding: utf-8 -*-
"""
Created on Mar 23, 2015

@author: noob
"""

from .base import ApiJob
from common.models import RegressionComment
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
import logging


class RComment(ApiJob):
    """
    commenting jobs for regression
    """

    http_method_names = ['post']

    @staticmethod
    def post(request, job):
        """
        if comment sent is empty, deletes existing comment
        :param request:
        :param job: job Object
        """

        try:
            try:
                author = request.yauser.login
            except:
                logging.exception('')
                author = request.POST.get('author', '')

            text = request.POST.get('comment', '')

            try:
                r_comment = RegressionComment.objects.get(job=job)
                if text:
                    r_comment.text = text
                    r_comment.author = author
                    r_comment.created_at = datetime.now()
                    r_comment.save()
                else:
                    r_comment.delete()
            except ObjectDoesNotExist:
                if text:
                    RegressionComment.objects.create(job=job, text=text, author=author, created_at=datetime.now())
                else:
                    pass
            return [{"success": 1}]
        except Exception as exc:
            logging.exception("Could not comment job {}".format(job.n))
            return [{"success": 0, "error": exc.__class__.__name__}]
