import os 
import subprocess
import urllib
import ssl
import ctypes
import shutil

pycharm_download_url = 'https://script-downloads.itarian.com/Pycharm/pycharm-community-2022.2.2.exe' ## change your pycharm download url here
download_path = "C:\\ProgramData\\Pycharm"

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():

	def uninstall(path):
		os.chdir(path)
		obj = subprocess.Popen('bin\uninstall.exe /S', shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
		out, err = obj.communicate()
		if err:
		    print(err)
		else:
			print("Pycharm uninstalled Succesfully..")
			return "Success"

	def Download(url,destination):
		try:
			gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
			download = urllib.urlretrieve(url,destination,context = gcontext)
			return "Success"			
		except Exception as e:
			return e

	def install(cmd):
		os.chdir(download_path)
		obj = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
		out, err = obj.communicate()
		if err:
		    print(err)
		else:
			print("Pycharm installed successfully...")
			return "Success"

	def pycharm():
		file_name = download_path+'\\Pycharm.exe'
		download = Download(pycharm_download_url,file_name) 
		if download == "Success":
			Install = install('Pycharm.exe /S /CONFIG=.\silent.config /D=C:\Program Files\JetBrains\PyCharm')
			if Install == "Success":
				print("Your System will restart in 2 minutes....")
				restart = os.popen('shutdown -r').read() 
			else:
				print("Error occurred while installing Pycharm...!")
		else:
			print("Error occurred while downloading Pycharm File...!")


	if os.path.exists(download_path):
		pass 
	else:
		os.makedirs(download_path)

	with open(download_path+'\\silent.config','w') as f:
		f.write("mode=admin\n")
		f.write("launcher32=1")

	if os.path.exists("C:\\Program Files\\JetBrains"):
		dir_list = os.walk('C:\\Program Files\\JetBrains').next()[1]
		if len(dir_list)>0:
			for val in dir_list:
				if os.path.exists("C:\\Program Files\\JetBrains\\"+val+'\\bin\\uninstall.exe'):
					print("Already a version of Pycharm is found in your device...")
					print("Uninstalling Pycharm...")
					Uninstall = uninstall('C:\\Program Files\\JetBrains\\'+val)
					if Uninstall == "Success":
						file_name = download_path+'\\Pycharm.exe'
						download = Download(pycharm_download_url,file_name)
						if download == "Success":
							Install = install('Pycharm.exe /S /CONFIG=.\silent.config /D=C:\Program Files\JetBrains\PyCharm')
							if Install == "Success":
								print("Your System will restart in 2 minutes....")
								restart = os.popen('shutdown -r').read()
							else:
								print("Error occurred while installing Pycharm...!")
						else:
							print("Error occurred while downloading Pycharm File...!")
					else:
						print("Error occurred while Uninstalling Pycharm...!")
				else:
					pass 
		else:
			pycharm()
	else:
		os.makedirs("C:\\Program Files\\JetBrains")
		pycharm()

