# Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""The RequestHandler for /job URLs."""

import json
import tornado

from functools import partial
from tornado.web import asynchronous

from handlers.base import BaseHandler
from models.job import (
    JOB_COLLECTION,
    JobDocument,
)
from utils.db import save
from utils.docimport import import_job_from_json
from taskqueue.tasks import send_emails


class JobHandler(BaseHandler):
    """Handle the /job URLs."""

    @property
    def collection(self):
        return self.db[JOB_COLLECTION]

    @property
    def accepted_keys(self):
        return ('job', 'kernel')

    @asynchronous
    def post(self, *args, **kwargs):
        if self.request.headers['Content-Type'] != self.accepted_content_type:
            self.send_error(status_code=415)
        else:
            json_obj = json.loads(self.request.body.decode('utf8'))
            if self.is_valid_put(json_obj):

                self.executor.submit(
                    partial(self._import, json_obj)
                ).add_done_callback(
                    lambda future:
                    tornado.ioloop.IOLoop.instance().add_callback(
                        partial(self._post_callback, future.result()))
                )

            else:
                self.send_error(status_code=400)

    def _import(self, json_obj):
        """Internal function to handle jobs import.

        Should be run on a separate thread.

        :param json_obj: The JSON-like object with the information.
        """
        response = import_job_from_json(json_obj)

        if response:
            result = save(self.db, response)

            job_id = (
                JobDocument.JOB_ID_FORMAT %
                (json_obj['job'], json_obj['kernel'])
            )
            send_emails.delay(job_id)

        return result

@@ -741,53 +741,8 @@
 son%0A
-import tornado%0A%0Afrom functools import partial
 %0Afro
@@ -837,22 +837,16 @@
  import 
-(%0A    
 JOB_COLL
@@ -855,103 +855,8 @@
 TION
-,%0A    JobDocument,%0A)%0Afrom utils.db import save%0Afrom utils.docimport import import_job_from_json
 %0Afro
@@ -891,16 +891,28 @@
 d_emails
+, import_job
 %0A%0A%0Aclass
@@ -1453,900 +1453,177 @@
     
-self.executor.submit(%0A                    partial(self._import, json_obj)%0A                ).add_done_callback(%0A                    lambda future:%0A                    tornado.ioloop.IOLoop.instance().add_callback(%0A                        partial(self._post_callback, future.result()))%0A                )%0A%0A            else:%0A                self.send_error(status_code=400)%0A%0A    def _import(self, json_obj):%0A        %22%22%22Internal function to handle jobs import.%0A%0A        Should be run on a separate thread.%0A%0A        :param json_obj: The JSON-like object with the information.%0A        %22%22%22%0A        response = import_job_from_json(json_obj)%0A%0A        if response:%0A            result = save(self.db, response)%0A%0A            job_id = (%0A                JobDocument.JOB_ID_FORMAT %25%0A                (json_obj%5B'job'%5D, json_obj%5B'kernel'%5D)%0A            )%0A            send_emails.delay(job_id)%0A%0A        return result
+import_job.apply_async(%5Bjson_obj%5D, link=send_emails.s())%0A                self._create_valid_response(200)%0A            else:%0A                self.send_error(status_code=400)
 %0A

Use celery task to import jobs.