import os
import yaml
import shutil
import subprocess
import time
import threading

# create folder
folder_path = "./servers"
server_list_path = "./servers.yml"
builder_path = "./builder"
builder_octoprint_config_path = f"{builder_path}/octoprint/octoprint/config.yaml"

def create_folder_if_not_exists(folder_path):
  if not os.path.exists(folder_path):
    os.makedirs(folder_path)

def copy_folder(source_folder, destination_folder):
  try:
    if os.path.exists(destination_folder):
      shutil.rmtree(destination_folder)

    shutil.copytree(source_folder, destination_folder)
  except Exception as e:
    print(f"Error copying folder: {e}")

def copy_file(source_file, destination_file):
  try:
    shutil.copy(source_file, destination_file)
  except Exception as e:
    print(f"Error copying file: {e}")


create_folder_if_not_exists(builder_path)

copy_file("./template/server-template/Dockerfile", "./builder/")

# read servers and octoprint template config

with open(server_list_path, 'r') as server_list_file:
  server_list = yaml.safe_load(server_list_file)

# update docker-compose in builder folder for each server in servers.yml

def run_docker_compose_up():
  try:
    subprocess.run(['docker', 'compose', 'up', '-d'], cwd='./builder/', check=True)
  except subprocess.CalledProcessError as e:
    print(f"Error executing 'docker-compose up': {e}")

def update_config_recursive(base_config, update_config):
  for key, value in update_config.items():
    if isinstance(value, dict):
      if key in base_config and isinstance(base_config[key], dict):
        update_config_recursive(base_config[key], value)
      else:
        base_config[key] = value  # Füge die gesamte neue Verschachtelung hinzu, falls noch nicht vorhanden
    else:
      base_config[key] = value

def replace_octoprint_config(server):
  with open(builder_octoprint_config_path, 'r') as file:
    config = yaml.safe_load(file)

  #config['appearance']['name'] = server['octoprint_config']['appearance']['name']

  update_config_recursive(config, server['octoprint_config'])

  with open(builder_octoprint_config_path, 'w') as file:
    yaml.dump(config, file)

for server in server_list['servers']:
  copy_folder("./template/octoprint/", "./builder/octoprint/")

  # update the docker-compose.yml
  with open('./template/server-template/docker-compose.yml', 'r') as file:
    file_content = file.read()

  file_content = file_content.replace('{{NAME}}', server['name'])
  file_content = file_content.replace('{{PORT}}', str(server['port']))

  with open(f'{builder_path}/docker-compose.yml', 'w') as file:
    file.write(file_content)

  replace_octoprint_config(server)

  run_docker_compose_up()
  """
  thread = threading.Thread(target=run_docker_compose_up)
  thread.start()
  """

  time.sleep(5)