from subprocess import PIPE, Popen
import ctypes
import os
import shutil

class MSTeams:
    
    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(self,CMD):
        with self.disable_file_system_redirection():
            OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE)
            out, err = OBJ.communicate()
            if out:
                print(out)
            else:
                print(err)
            
    def checkingAndClearingMSTeams(self):
        if os.path.exists(os.environ["LOCALAPPDATA"] + r"\Microsoft\Teams"):
            if os.path.exists(os.environ["APPDATA"] + r"\Microsoft\Teams"):
                processes = os.popen("tasklist").read()
                if "Teams.exe" in processes:
                    self.executecmd("taskkill /f /im Teams.exe")
                shutil.rmtree(os.environ["APPDATA"] + r"\Microsoft\Teams", ignore_errors = True)
                print("successfully cleaned the Teams client cache")
            else:
                print("microsoft teams files are not found")
        else:
            print("microsoft teams is not found. please install the microsoft teams")
            
MSobj = MSTeams()

MSobj.checkingAndClearingMSTeams()
