import requests
import os
import configparser
from configparser import ConfigParser
import tkinter as tk
import zipfile
root = tk.Tk()
root.title("Ez-Setup")
root.geometry("600x400")

def clear_screen():
    for child in root.winfo_children(): 
        child.destroy()


label = tk.Label(root, text="Ez-Setup")
label.pack(pady=20) # Add some padding
def get_entry_text():
    """Retrieves and prints the text from the Entry widget."""
    new_value = add_link.get()
    add_link.delete(0, tk.END)
    config1 = ConfigParser()
    config1.read('links.ini')
    section_Name = 'links'
    all_keys = []
    if section_Name in config1:
        for key in config1[section_Name]:
            all_keys.append(key)
    length = len(all_keys) + 1

    new_key = str(length)
    new_value = new_value.replace("%", "%%")

    if not config1.has_section(section_Name):
        config1.add_section(section_Name)

    config1.set(section_Name, new_key, new_value)
    with open('links.ini', 'w') as configfile:
        config1.write(configfile)

# Create a button widget
def add_link_to_ini():
    clear_screen()
    global add_link
    add_link = tk.Entry(root, width=30)  # width in characters
    add_link.pack(pady=10)
    global submit_button
    submit_button = tk.Button(root, text="Submit Link", command=get_entry_text)
    submit_button.pack()
    global back_button1
    back_button1 = tk.Button(root, text="Back", command=main)
    back_button1.place(x=5, y=5)

def download_files():
    clear_screen()
    config = configparser.ConfigParser()
    config.read('links.ini')

    section_name = 'links'
    if section_name in config:
        items = config.items(section_name)
        links_list = [value for key, value in items]
        print(links_list)
    else:
        print(f"Section '{section_name}' not found.")

    def download_file(url, destination_folder):
        """
        Downloads a file from a given URL to a specified destination folder.

        Args:
            url (str): The URL of the file to download.
            destination_folder (str): The path to the folder where the file should be saved.
        """
        try:
            # Create the destination folder if it doesn't exist
            os.makedirs(destination_folder, exist_ok=True)

            # Get the filename from the URL
            filename = os.path.basename(url)

            # Construct the full path for saving the file
            file_path = os.path.join(destination_folder, filename)

            # Send a GET request to the URL
            response = requests.get(url, stream=True)
            response.raise_for_status()  # Raise an exception for bad status codes

            # Write the content to the file in chunks to handle large files
            with open(file_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)

            print(f"File '{filename}' downloaded successfully to '{destination_folder}'")

        except requests.exceptions.RequestException as e:
            print(f"Error downloading file: {e}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")


    # Example usage:
    target_directory = "./Downloads"  # Replace with your desired path

    for link in links_list:
        download_file(link, target_directory)
    directory = os.getcwd() + "\Downloads"
    for name in os.listdir(directory):
        if name.lower().endswith('.exe'):
            os.startfile(directory+"\\"+name)
        if name.lower().endswith('.msi'):
            os.startfile(directory+"\\"+name)
    main()
def main():
    clear_screen()
    global button1
    button1 = tk.Button(root, text="Add Link", command=add_link_to_ini, width=30, height=2)
    button1.pack()
    global button2
    button2 = tk.Button(root, text="Download Files", command=download_files, width=30, height=2)
    button2.pack()

main()
# Start the event loop
root.mainloop()