import os
import re
import sys
import stat
import time
from UmenuUtils import Utils

class Commander(object):
    def __init__(self, nextdict):
        ### Deep copy nextdict for minimial side effects later
        self.data = {}
        for key in nextdict.keys():
            self.data[key] = nextdict[key]
        self.user = os.environ['USER']
        self.fname = os.environ['HOME'] + '/umenu2_tempp_' + self.user + '_' + Utils.yyyymmddhhmmss_now() + '.ush'

    def import_conf_pieces(self, cnf):
        """
        I want to minimize interaction between Commander and Conf
        Need to know basis, and all that.
        """
        self.progdir = cnf.cnf['prog']
        self.diag = cnf.cnf['diag']

    def run_script(self):
        self.make_script_line_array()
        f = open(self.fname, 'w')
        for line in self.lines:
            print(line, file=f)
        f.close()
        os.chmod(self.fname,stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR )
        if 'bkground' in self.data and self.data['bkground'] == 't':
            print('')
            cmd='{}/ufork.py {}'.format(self.progdir, self.fname)
            os.system(cmd)
            print('')
        else:
            os.system(self.fname)
        if 'stop' in self.data and self.data['stop']:
            Utils.printraw('Hit Enter key to return to menu system==>')
            sys.stdin.readline()
        #print('self.diag={}'.format(self.diag))
        #time.sleep(3)
        if not self.diag:
            self.delete_script_file()

    def delete_script_file(self):
        if not os.fork():   # if this is the child
            time.sleep(2)   # plenty of time,regardless of how slow the command starts
            os.remove(self.fname) #child does the removal
            sys.exit(0)           #child intentionally terminates

    @classmethod
    def prompted_argument_substitution(self,strg):
        questions={}
        tokens = re.findall(r'(%[^%]%[^%]+%%)', strg)
        for token in sorted(tokens):
            questions[token] = {}
            q = re.sub('^%.%', '', token)
            q = re.sub('%%$', '', q)
            questions[token]['q'] = q
            Utils.printraw(q + '==>')
            questions[token]['a'] = sys.stdin.readline().strip()
            print('')
        returnstring = strg
        for token in questions:
            returnstring = re.sub(token, questions[token]['a'], returnstring)
        return returnstring


    def make_script_line_array(self):
        self.lines = []
        self.lines.append('#!/bin/sh')
        self.lines.append('### ' + self.fname)
        self.lines.append('orgdir=`pwd`')
        keys = self.data.keys()
        if 'dir' in keys:
            self.lines.append('cd {}'.format(self.data['dir']))
        else:
            self.lines.append('cd {}'.format(self.progdir))
        if 'path' in keys and len(self.data['path']) > 0 and not str.isspace(self.data['path']):
            self.lines.append('PATH={}:$PATH'.format(self.data['path']))
        if 'env' in self.data:
            if type(self.data['env']) == list or type(self.data['env']) == tuple or False:
                self.lines.append('export ' + ' '.join(self.data['env']))
            elif type(self.data['env']) == str:
                self.lines.append('export ' + self.data['env'])
        if 'cmd' in self.data:
            if type(self.data['cmd']) == list or type(self.data['cmd']) == tuple:
                mycmd = ' '.join(self.data['cmd'])
            elif type(self.data['cmd']) == str:
                mycmd = self.data['cmd']
            if 'bkground' in self.data and self.data['bkground']:
                temp='{}/ufork.py '.format(self.progdir)
                mycmd = temp + mycmd 
            self.lines.append(Commander.prompted_argument_substitution(mycmd))
        #print('')



# /* vim: set foldmethod=indent: */
