# -*- coding:utf-8 -*-

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import uuid
import json
import threading
import delegator
from tpl import path
from tpl import prompt
from tpl import errors


DEFAULT_PY_GLOBALS = {
    'os': os,
    'sys': sys,
    'json': json,
    'path': path,
    'mdfifo': os.mkfifo,
    'prompt': prompt
}

DEFAULT_PY_LOCALS = {
    'context_pipe': None
}

DEFAULT_SHELL_VARS = {
    'pipe': None
}


class PyExec(threading.Thread):
    def __init__(self, command, injected_globals, injected_locals):
        self.command = command
        self.injected_globals = injected_globals
        self.injected_locals = injected_locals
        super(PyExec, self).__init__(name='py_exec_tpl_constructor')

    def run(self):
        exec(self.command, self.injected_globals, self.injected_locals)


def py_execute(command, injected_globals=None, injected_locals=None):
    injected_globals = injected_globals or {}
    injected_locals = injected_locals or {}
    injected_globals.update(DEFAULT_PY_GLOBALS)
    pipe_path = '/tmp/{}.pipe'.format(str(uuid.uuid4()))
    os.mkfifo(pipe_path)
    DEFAULT_PY_LOCALS['context_pipe'] = pipe_path
    injected_locals.update(DEFAULT_PY_LOCALS)
    command = '{};pipe=open(context_pipe, "w");pipe.write(json.dumps(context));pipe.close()'.format(command)
    PyExec(command, injected_globals, injected_locals).start()
    pipe = open(pipe_path)
    context = json.loads(pipe.read())
    pipe.close()
    return context


class ShellExec(threading.Thread):
    def __init__(self, command, injected_vars=None):
        self.command = command
        self.injected_vars = injected_vars
        super(ShellExec, self).__init__(name='shell_exec_tpl_constructor')

    def run(self):
        command = self.command
        for key, value in self.injected_vars.items():
            command = ' && '.join([
                '{}={}'.format(key, value),
                command
            ])
        command_res = delegator.run(command, block=True)
        if command_res.return_code != 0:
            raise errors.ShellExecError(command_res.return_code,
                                        command_res.out,
                                        command_res.err)


def shell_execute(command):
    pipe_path = '/tmp/{}.pipe'.format(str(uuid.uuid4()))
    os.mkfifo(pipe_path)
    DEFAULT_SHELL_VARS['pipe'] = pipe_path
    ShellExec(command, DEFAULT_SHELL_VARS).start()
    pipe = open(pipe_path)
    c = pipe.read()
    c.strip()
    context = json.loads(c)
    pipe.close()
    return context



@@ -1085,86 +1085,40 @@
     
-pipe_path = '/tmp/%7B%7D.pipe'.format(str(uuid.uuid4()))%0A    os.mkfifo(pipe_path)%0A
+with path.TempPipe() as tp:%0A    
     
@@ -1145,32 +1145,35 @@
 ontext_pipe'%5D = 
+tp.
 pipe_path%0A    in
@@ -1162,24 +1162,28 @@
 p.pipe_path%0A
+    
     injected
@@ -1216,24 +1216,28 @@
 LOCALS)%0A    
+  
+  
 command = '%7B
@@ -1329,16 +1329,20 @@
 ommand)%0A
+    
     PyEx
@@ -1400,39 +1400,16 @@
 t()%0A    
-pipe = open(pipe_path)%0A
     cont
@@ -1425,16 +1425,19 @@
 n.loads(
+tp.
 pipe.rea
@@ -1441,33 +1441,16 @@
 read())%0A
-    pipe.close()%0A
     retu

update temp pipe context