'''
Created on 20/10/2017

@author: bgw
'''

from datetime import datetime, timedelta
import sys
import getopt
import pycurl
import subprocess


USERNAME = "USERNAME"
PASSWORD = "PASSWORD"

ADDTIMEOPTIONS = ('Qtr', 'mQtr', 'Half', 'Hour', 'Day')
try:
    # python 3
    from urllib.parse import urlencode
except ImportError:
    # python 2
    from urllib import urlencode


def setin():
    ''' Sets IN/OUT status to IN '''
    now = datetime.now()

    nexthour = (now + timedelta(hours=1)).strftime("%H:%M+%a+%d+%b")
    nextday = '08:30+{}'.format((now + timedelta(days=1)).strftime("%a+%d+%b"))
    setstatus(nexthour, nextday)

    print "Set status to IN"

def setfinishedforday():
    ''' Sets IN/OUT status to Finished for the Day '''
    now = datetime.now()

    nexthour = (now + timedelta(hours=1)).strftime("%H:%M+%a+%d+%b")
    nextday = '08:30+{}'.format((now + timedelta(days=1)).strftime("%a+%d+%b"))

    setstatus(nexthour, nextday, staddtime='Day', stwhere='Finished+for+the+day')

    print "Set status to Finished for day"

def setout(location, changestr='Qtr'):
    ''' Sets IN/OUT status to provided location for provided time '''


    if changestr not in ADDTIMEOPTIONS:
        helpme()

    location = location.replace(" ", "+")

    now = datetime.now()

    nexthour = (now + timedelta(hours=1)).strftime("%H:%M+%a+%d+%b")
    nextday = '08:30+{}'.format((now + timedelta(days=1)).strftime("%a+%d+%b"))


    setstatus(nexthour, nextday, staddtime=changestr, stwhere=location)

    print "Put you at %s for %s" % (location, changestr)


def setstatus(nxhour, nxday, sttype='', staddtime='Auto', stwhere='In', stback=''):
    '''Creates the data string and performs the pycurl request'''

    data = "NextHour={}&NextDay={}&Type={}&AddTime={}&Where={}&BackAt={}".format(nxhour, nxday,
                                                                                 sttype, staddtime,
                                                                                 stwhere, stback)
    url_dir = "http://intranet.powernet.inet/Staff/MyInOut.asp"
    conn = pycurl.Curl()
    conn.setopt(pycurl.URL, url_dir)
    conn.setopt(pycurl.POSTFIELDS, data)
    conn.setopt(pycurl.USERPWD, "{}:{}".format(USERNAME, PASSWORD))
    conn.setopt(pycurl.VERBOSE, 0)

    conn.perform()
    conn.close()

def helpme():
    ''' Prints out how to use this program '''
    print "InOut.py"
    print "\n\nCommands: \n"
    print "-h: Brings up help (This), or"
    print "-i: Set to in, or"
    print "-f: Finished for the day, or"
    print "-m: Start Outlook"
    print "-o 'LOCATION','TIME TO ADD': Puts status to 'LOCATION' and adds specified 'TIME'."
    print "If -o is called must provide 'LOCATION' and 'TIME TO ADD'"
    print "TIME must be in the following list:"
    print "'Qtr' - 15 mins\n'mQtr' - negative 15 mins"
    print "'Half' - 30 mins\n'Hour' - an hour\n'Day' - a day"
    exit(1)


def startoutlook():
    try:
        subprocess.Popen("C:\Program Files (x86)\Microsoft Office\Office16\OUTLOOK.EXE")
    except:
        try:
            subprocess.Popen("C:\Program Files (x86)\Microsoft Office\Office14\OUTLOOK.EXE")
        except:
            print("Couldn't find the location of your version of Outlook")



def main(argv):
    ''' Performs the required function call depending on the input arguments '''


    try:
        opts, args = getopt.getopt(argv, "hmifo:")
    except getopt.GetoptError:
        helpme()
    if opts == []:
        helpme()
    for opt, arg in opts:
        print opt,arg

        if opt == '-h':
            helpme()
        if opt == "-i":
            setin()
        if opt == "-m":
            startoutlook()
        if opt == "-o":
            arguments = arg.split(",")
            if len(arguments) != 2:
                helpme()
            setout(arguments[0], arguments[1])
        if opt == "-f":
            setfinishedforday()



if __name__ == '__main__':
    main(sys.argv[1:])

@@ -3026,24 +3026,70 @@
 outlook():%0D%0A
+    if not processExists('OUTLOOK.EXE'):%0D%0A    
     try:%0D%0A  
@@ -3078,32 +3078,36 @@
 %0D%0A        try:%0D%0A
+    
         subproce
@@ -3180,24 +3180,28 @@
 .EXE%22)%0D%0A    
+ 
+   
 except:%0D%0A   
@@ -3197,38 +3197,46 @@
 xcept:%0D%0A        
+    
 try:%0D%0A
+    
             subp
@@ -3313,32 +3313,36 @@
 .EXE%22)%0D%0A        
+  
+  
 except:%0D%0A       
@@ -3326,32 +3326,36 @@
        except:%0D%0A
+    
             prin
@@ -3412,24 +3412,761 @@
 utlook%22)%0D%0A%0D%0A
+def processExists(processname):%0D%0A    tlcall = 'TASKLIST', '/FI', 'imagename eq %25s' %25 processname%0D%0A    # shell=True hides the shell window, stdout to PIPE enables%0D%0A    # communicate() to get the tasklist command result%0D%0A    tlproc = subprocess.Popen(tlcall, shell=True, stdout=subprocess.PIPE)%0D%0A    # trimming it to the actual lines with information%0D%0A    tlout = tlproc.communicate()%5B0%5D.strip().split('%5Cr%5Cn')%0D%0A    # if TASKLIST returns single line without processname: it's not running%0D%0A    if len(tlout) %3E 1 and processname in tlout%5B-1%5D:%0D%0A        #print('process %22%25s%22 is running!' %25 processname)%0D%0A        return True%0D%0A    else:%0D%0A        #print(tlout%5B0%5D)%0D%0A        #print('process %22%25s%22 is NOT running!' %25 processname)%0D%0A        return False
 %0D%0A%0D%0Adef main

Check process exists