#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: __init__.py 9634 2016-04-13 08:13:53Z Eric $
#
# Copyright (c) 2012 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Eric $
# $Date: 2016-04-13 16:13:53 +0800 (Wed, 13 Apr 2016) $
# $Revision: 9634 $
"""
Celery tasks which should be run at cloud worker.
"""

import os
import time
import datetime
import logging
import inspect

#from celery import task
from Iuno.cloud.queue.App import app

try:
    import lzma # Python 3.3
except ImportError:
    import pylzma as lzma

from .. import HTTP_METHOD
from .. import Config, Request

logger = logging.getLogger(__name__)

@app.task
def send(request, engine):
    """
    Send job implementation.
    
    @param request AyncRequest instance.
    @param engine Browser implementation engine.
    @return AyncResponse.
    """
    method = request.method
    if not method:
        method = 'get'
        
    kws = dict([(arg, getattr(request, arg)) 
                for arg in inspect.getargspec(Request.__init__)[0]
                if hasattr(request, arg)])
    kws.pop('url', None)
    kws.pop('method', None)
    
    func = HTTP_METHOD.get(method, None)
    if func:
        response = func(request.url, engine=engine, async=False, **kws)
    else:
        raise NotImplementedError('Not implemented method: %s' % method)

    response.content = lzma.compress(response.content)
    response.snapshot = lzma.compress(response.snapshot)
    
    return response
