# :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.

import pickle
import base64
try:
    from shlex import quote
except ImportError:
    from pipes import quote

import qb

from .base import Processor
from .. import pickle_support


class QubeProcessor(Processor):
    '''Foreground processor.'''
    
    def process(self, command, args=None, kw=None):
        '''Process *command* with *args* and *kw*.'''
        if args is None:
            args = ()
        
        if kw is None:
            kw = {}
        
        serialised = base64.b64encode(
            pickle.dumps(
                {'command': command, 'args': args, 'kw': kw},
                pickle.HIGHEST_PROTOCOL
            )
        )
        
        python_statement = (
            'import pickle;'
            'import base64;'
            'data = base64.b64decode(\'{0}\');'
            'data = pickle.loads(data);'
            'data[\'command\'](*data[\'args\'], **data[\'kw\'])'
        ).format(serialised.replace("'", r"\'"))

        command = []
        if self.host is None:
            command.extend('python')
        else:
            command.extend(self.host.get_python_prefix())
        
        command.extend(['-c', python_statement])

        job = {
            'prototype': 'cmdline',
            'name': 'segue',
            'cpus': 1,
            'package': {
                'cmdline': ' '.join(command)
            }
        }
        
        job_id = qb.submit(job)
        
        return 'Submitted Qube job: {0}'.format(job_id)


@@ -212,19 +212,8 @@
 te%0A%0A
-import qb%0A%0A
 from
@@ -1274,16 +1274,266 @@
    job =
+ self._create_job(command)%0A        job_id = self._submit_job(job)%0A        %0A        return 'Submitted Qube job: %7B0%7D'.format(job_id)%0A    %0A    def _create_job(self, command):%0A        '''Create and return the Qube job for the *command*.'''%0A        return
  %7B%0A     
@@ -1717,44 +1717,77 @@
     
+%0A
     
-%0A        job_id = qb.submit(job)
+def _submit_job(self, job):%0A        '''Submit the *job* to Qube.
 %0A   
@@ -1804,53 +1804,175 @@
     
-r
+R
 eturn 
-'Submitted Qube job: %7B0%7D'.forma
+the job id.%0A        %0A        '''%0A        # Import here so that subclasses can avoid qb import if desired.%0A        import qb%0A        %0A        return qb.submi
 t(job
-_id
 )%0A%0A

Support easier tailoring of Qube processor by adding more granular methods.