import re
from datetime import datetime, timedelta
import ctypes
import os
import subprocess


UserName = "Test" # Provide logged in user name
Command = itsm.getParameter('Command')  # data type should be string
Args = itsm.getParameter('Args')  # data type should be string
daYs = itsm.getParameter('daYs')  # data type should be integer
taskName = itsm.getParameter('taskName')  # Change the name if required. New task will be replaced if the task has same name data type should be string


class disable_file_system_redirection():
    _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
    _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

    def __enter__(self):
        self.old_value = ctypes.c_long()
        self.success = self._disable(ctypes.byref(self.old_value))

    def __exit__(self, type, value, traceback):
        if self.success:
            self._revert(self.old_value)


# with disable_file_system_redirection():
#    username = os.path.basename(os.popen(r'whoami').read()).replace('\n', '')
#    sid = os.popen(r'wmic useraccount where name="' + username + r'" get sid').read().splitlines()[1].strip()


def ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(["powershell", cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        return out, err


def setTakSchXml(psCommand, args, dys, TaskName, SID):
    Current_time = datetime.now()
    TimeForTask = Current_time + timedelta(days=dys)
    Date = datetime.strftime(TimeForTask, "%Y-%m-%d")
    Time = datetime.strftime(Current_time, "%H:%M:%S")
    XML = r'''<?xml version="1.0" encoding="UTF-16"?>
        <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
          <Triggers>
            <LogonTrigger>
                <Enabled>true</Enabled>
                <UserId>''' + SID + r'''</UserId>
                <EndBoundary>''' + Date + 'T' + Time + r'''</EndBoundary>
            </LogonTrigger>
          </Triggers>
          <Principals>
            <Principal id="Author">
              <UserId>''' + SID + r'''</UserId>
              <RunLevel>HighestAvailable</RunLevel>
            </Principal>
          </Principals>
          <Settings>
            <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
            <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
            <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
            <AllowHardTerminate>true</AllowHardTerminate>
            <StartWhenAvailable>false</StartWhenAvailable>
            <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
            <IdleSettings>
              <StopOnIdleEnd>true</StopOnIdleEnd>
              <RestartOnIdle>false</RestartOnIdle>
            </IdleSettings>
            <AllowStartOnDemand>true</AllowStartOnDemand>
            <Enabled>true</Enabled>
            <Hidden>false</Hidden>
            <RunOnlyIfIdle>false</RunOnlyIfIdle>
            <WakeToRun>false</WakeToRun>
            <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
            <Priority>7</Priority>
          </Settings>
          <Actions Context="Author">
            <Exec>
                <Command>''' + psCommand + r'''</Command>
                <Arguments>''' + args + r'''</Arguments>
            </Exec>
          </Actions>
        </Task>'''

    ConfigPath = os.environ['Temp'] + r'\TaskXMLConfig.xml'
    with open(ConfigPath, 'wb') as xmlFile:
        xmlFile.write(XML)
        xmlFile.close()

    cmd = r'schtasks /create /tn "' + TaskName + r'" /XML ' + '"' + ConfigPath + '"'
    if os.path.exists(ConfigPath):
        result = ExecuteCmd(cmd)
        #  os.remove(ConfigPath)
        if result[0] != '':
            print result[0]
            return True
        else:
            print result[1]
    else:
        print "Config file does not exists"


sid = ExecuteCmd(r'(Get-LocalUser -Name "' + UserName + r'" | Select sid).sid.value')[0].replace('\r\n', '')
# Command = r'"C:\Users\%username%\AppData\Roaming\Telegram Desktop\unins000.exe" /SILENT'
ExecuteCmd('Unregister-ScheduledTask -TaskName "' + taskName + '" -Confirm:$false')
if sid != '':
    res = setTakSchXml(Command, Args, daYs, taskName, sid)
    if res:
        print "Task Scheduled"
    else:
        print "Task not scheduled"
else:
    print "Provide valid user name"		
    