# vim: tabstop=4 shiftwidth=4 softtabstop=4

#    Copyright 2013 Rackspace
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import webob.exc

from qonos.api import api
from qonos.api.v1 import api_utils
from qonos.common import exception
from qonos.common import timeutils
from qonos.common import utils
import qonos.db
from qonos.openstack.common._i18n import _
from qonos.openstack.common import wsgi


CONF = api.CONF


class JobsController(object):

    def __init__(self, db_api=None):
        self.db_api = db_api or qonos.db.get_api()

    def list(self, request):
        params = request.params.copy()

        try:
            params = utils.get_pagination_limit(params)
        except exception.Invalid as e:
            raise webob.exc.HTTPBadRequest(explanation=str(e))

        if 'status' in params:
            params['status'] = str(params['status']).upper()

        if 'timeout' in params:
            timeout = timeutils.parse_isotime(params['timeout'])
            params['timeout'] = timeutils.normalize_time(timeout)

        if 'hard_timeout' in params:
            hard_timeout = timeutils.parse_isotime(params['hard_timeout'])
            params['hard_timeout'] = timeutils.normalize_time(hard_timeout)

        try:
            jobs = self.db_api.job_get_all(params)
        except exception.NotFound:
            raise webob.exc.HTTPNotFound()

        limit = params.get('limit')
        if len(jobs) != 0 and len(jobs) == limit:
            next_page = '/v1/jobs?marker=%s' % jobs[-1].get('id')
        else:
            next_page = None

        for job in jobs:
            utils.serialize_datetimes(job)
            api_utils.serialize_job_metadata(job)