"""
Copyright 2015 Hewlett-Packard

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 time

import falcon

from freezer_api.api.common import resource
from freezer_api.common import exceptions as freezer_api_exc
from freezer_api import policy


class SessionsCollectionResource(resource.BaseResource):
    """
    Handler for endpoint: /v1/sessions
    """
    def __init__(self, storage_driver):
        self.db = storage_driver

    @policy.enforce('sessions:get_all')
    def on_get(self, req, resp):
        # GET /v1/sessions(?limit,offset)     Lists sessions
        user_id = req.get_header('X-User-ID')
        offset = req.get_param_as_int('offset') or 0
        limit = req.get_param_as_int('limit') or 10
        search = self.json_body(req)
        obj_list = self.db.search_session(user_id=user_id, offset=offset,
                                          limit=limit, search=search)
        resp.body = {'sessions': obj_list}

    @policy.enforce('sessions:create')
    def on_post(self, req, resp):
        # POST /v1/sessions    Creates session entry
        doc = self.json_body(req)
        if not doc:
            raise freezer_api_exc.BadDataFormat(
                message='Missing request body')
        user_id = req.get_header('X-User-ID')
        session_id = self.db.add_session(user_id=user_id, doc=doc)
        resp.status = falcon.HTTP_201
        resp.body = {'session_id': session_id}


class SessionsResource(resource.BaseResource):
    """
    Handler for endpoint: /v1/sessions/{session_id}
    """

    def __init__(self, storage_driver):
        self.db = storage_driver

    @policy.enforce('sessions:get')
    def on_get(self, req, resp, session_id):
        # GET /v1/sessions/{session_id}     retrieves the specified session
        # search in body
        user_id = req.get_header('X-User-ID') or ''
        obj = self.db.get_session(user_id=user_id, session_id=session_id)
        if obj:
            resp.body = obj
        else:
            resp.status = falcon.HTTP_404

    @policy.enforce('sessions:delete')
    def on_delete(self, req, resp, session_id):
        # DELETE /v1/sessions/{session_id}     Deletes the specified session
        user_id = req.get_header('X-User-ID')
        obj = self.db.get_session(user_id=user_id,
                                  session_id=session_id)
        if not obj:
            raise freezer_api_exc.DocumentNotFound(
                message='No session found with ID:{0}'.
                format(session_id))
        else:
            self.db.delete_session(user_id=user_id, session_id=session_id)
            resp.body = {'session_id': session_id}
            resp.status = falcon.HTTP_204

    @policy.enforce('sessions:update')
    def on_patch(self, req, resp, session_id):
        # PATCH /v1/sessions/{session_id}     updates the specified session
        user_id = req.get_header('X-User-ID') or ''
        doc = self.json_body(req)
        new_version = self.db.update_session(user_id=user_id,
                                             session_id=session_id,
                                             patch_doc=doc)
        resp.body = {'session_id': session_id, 'version': new_version}

    @policy.enforce('sessions:replace')
    def on_post(self, req, resp, session_id):
        # PUT /v1/sessions/{session_id} creates/replaces the specified session
        user_id = req.get_header('X-User-ID') or ''
        doc = self.json_body(req)
        if not doc:
            raise freezer_api_exc.BadDataFormat(
                message='Missing request body')
        new_version = self.db.replace_session(user_id=user_id,
                                              session_id=session_id,
                                              doc=doc)
        resp.status = falcon.HTTP_201
        resp.body = {'session_id': session_id, 'version': new_version}


class SessionsAction(resource.BaseResource):
    """
    Handler for endpoint: /v1/sessions/{session_id}/action
    """

    def __init__(self, storage_driver):
        self.db = storage_driver

    @policy.enforce('sessions:action:create')
    def on_post(self, req, resp, session_id):
        # POST /v1/sessions/{session_id}/action
        # executes an action on the specified session

        user_id = req.get_header('X-User-ID') or ''
        doc = self.json_body(req)

        try:
            action, params = next(iter(doc.items()))
        except Exception:
            raise freezer_api_exc.BadDataFormat("Bad action request format")

        session_doc = self.db.get_session(user_id=user_id,
                                          session_id=session_id)
        session = Session(session_doc)
        session.execute_action(action, params)

        if session.need_update:
            self.db.update_session(user_id=user_id,