import ctypes
import glob
import os
import subprocess


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)


def ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        if out == '':
            return 0
        else:
            return out


def uninstallDoPDF():
    resA = ExecuteCmd(['powershell', r'wmic product get name | Select-String -pattern "doPDF"'])
    if not resA:
        print("doPDF products does not exists")
    else:
        path = r'C:\ProgramData\Package Cache'
        if os.path.exists(path):
            UninstallPath = glob.glob(path + r'\*\novapdf.exe')
            if len(UninstallPath) == 1:
                CMD = '"' + UninstallPath[0] + '" /uninstall /quiet'
                ExecuteCmd(CMD)
                resB = ExecuteCmd(['powershell', r'wmic product get name | Select-String -pattern "DoPDF"'])
                if not resB:
                    print("DoPDF products removed successfully")
                else:
                    print "Unable to uninstall DoPDF"
            else:
                print "Unable to uninstall DoPDF"
        else:
            print "Unable to uninstall DoPDF"

			
uninstallDoPDF()