import subprocess
import PyPDF2
import os
import shutil
import sys


def clear_workspace(files):
  if not files or not isinstance(files, list) or len(files) == 0:
    return
  
  for file in files:
    if os.path.exists(file):
      os.remove(file)


def delete_folder(folder_path):
    try:
        shutil.rmtree(folder_path)
    except Exception as e:
        print(f"Error deleting the folder {folder_path}: {e}")


def merge_pdfs(pdf1_path, pdf2_path, output_path):
    # open the two PDF files
    with open(pdf1_path, 'rb') as file1, open(pdf2_path, 'rb') as file2:
        # create PDF-Reader-Objects
        pdf1_reader = PyPDF2.PdfReader(file1)
        pdf2_reader = PyPDF2.PdfReader(file2)
        
        # create PDF-Writer-Object
        pdf_writer = PyPDF2.PdfWriter()
        
        # add pages from the first PDF
        for page_num in range(len(pdf1_reader.pages)):
            page = pdf1_reader.pages[page_num]
            pdf_writer.add_page(page)
        
        # add pages from the second PDF
        for page_num in range(len(pdf2_reader.pages)):
            page = pdf2_reader.pages[page_num]
            pdf_writer.add_page(page)
        
        # save the combined PDF
        with open(output_path, 'wb') as output_file:
            pdf_writer.write(output_file)


# If a script failes the files are moved to the old_files directory so we need to move them back so that the paths defined in the files are correct
def move_files_back_from_old_files():
  # check if old_files directory exists and move files back
  if os.path.exists("oldFiles"):
    for file in os.listdir("oldFiles"):
      shutil.move(os.path.join("oldFiles", file), file)
    os.rmdir("oldFiles")


# copy the tasks files from another task to the current runningTasks to execute it
# be aware of that in your work directory the python script has not the same name as the target script because it will be overwriten
def execute_another_group_task(folder_path, script_file_name):
  work_directory = os.getcwd() # get current folder path

  copy_files(folder_path, work_directory)
  clear_workspace(["index.json", "requirements.txt"])

  execute_python_file(script_file_name)


def execute_python_file(file_path):
  if not os.path.exists(file_path):
    print(f"The file {file_path} does not exist.")
    sys.exit(1)
    return

  if not file_path.endswith('.py'):
    print("The specified file is not a Python file.")
    sys.exit(1)
    return

  try:
    #base_dir = os.path.dirname(os.path.abspath(file_path))
    #os.chdir(base_dir)  # Change to the directory of the script
    subprocess.run(['python3.9', os.path.basename(file_path)] + sys.argv[1:], check=True)
  except subprocess.CalledProcessError as e:
    print(f"Error executing the file: {e}")
    sys.exit(1)
  except Exception as e:
    print(f"An unexpected error occurred: {e}")
    sys.exit(1)


def copy_files(source_folder, destination_folder):
  if not os.path.exists(source_folder):
    print(f"The source folder {source_folder} does not exist.")
    sys.exit(1)
    return
  
  if not os.path.exists(destination_folder):
    print(f"The destination folder {destination_folder} does not exist.")
    sys.exit(1)
    return
  
  try:
    # List all files in the source folder
    files = os.listdir(source_folder)
    
    # Copy each file to the destination folder
    for file in files:
      source_path = os.path.join(source_folder, file)
      destination_path = os.path.join(destination_folder, file)
      shutil.copy2(source_path, destination_path)
    
  except Exception as e:
    print(f"An error occurred while copying files: {e}")
    sys.exit(1)