import zipfile
import os
import requests


def safe_unzip_file(zip_path, extract_to):

    # Check if the file exists
    if not os.path.exists(zip_path):
        print("Error: ZIP file not found.")
        return

    # Check if the file is a valid ZIP file
    if not zipfile.is_zipfile(zip_path):
        print("Error: The file is not a valid ZIP file.")
        return

    try:
        with zipfile.ZipFile(zip_path, "r") as zip_ref:
            # Extract all the contents
            zip_ref.extractall(extract_to)
            print("All files extracted successfully.")
    except zipfile.BadZipFile:
        print("Error: Corrupted ZIP file.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")


def download_database(url, filename):
    # Download a file from the given URL
    print(f"Downloading {url}")
    response = requests.get(url)
    if response.status_code == 200:
        with open(filename, "wb") as file:
            file.write(response.content)
        print(f"Download of \n  {url} \n completed successfully.")
    else:
        print("Failed to retrieve the file.")


def download_databases(project_settings):
    databases = [
        "https://webdata.illumina.com/downloads/productfiles/humanmethylation450/humanmethylation450_15017482_v1-2.csv",
        "https://downloads.thebiogrid.org/Download/BioGRID/Release-Archive/BIOGRID-4.4.231/BIOGRID-ORGANISM-4.4.231.tab.zip",
    ]
    download_to_folder = project_settings["project_path"]
    for database in databases:
        donwload_to_fname = os.path.join(download_to_folder, os.path.basename(database))
        download_database(database, donwload_to_fname)
        # TODO
        # if biogrid:
            # safe_unzip_file(donwload_to_fname, download_to_folder) 
            # find the one that contains homo sapiens data
            # remove else
            # update project settings
      
