# funct_gen.py
from functions import *
import os
import time
import pandas as pd
import paramiko
import yaml
import shutil


# Function to generate the CFG_DMUAUT.SPF configuration file and save selected parameter sets
def gen_cfg_dmuaut(folder_output, input_vars, selected_params, filetransfer=False):
    filename = "CFG_DMUAUT.SPF"

    # Get the current timestamp for folder name (format: YYMMDD_HHmmSS)
    timestamp = time.strftime("%y%m%d_%H%M%S")
    folder_path = os.path.join(folder_output, f"{timestamp}")

    # Create the folder with the timestamp
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    # Define the file path for the SPF configuration file
    spf_file_path = os.path.join(folder_path, filename)

    # Generate the SPF file content
    with open(spf_file_path, "w") as spf_file:
        spf_file.write(f"; CFG FILE FOR DMU50 AUTOMATION\n")
        spf_file.write(f"; GENERATED: {timestamp}\n")
        spf_file.write("; ---------------------------------------------------\n")

        # Iterate over the input variables (each group), and write them into the file
        for group_name, variables in input_vars.items():
            for var_name, var_value in variables.items():
                spf_file.write(f"{var_name.upper()} = {var_value.get()}     ; {VarDescription(var_name)} \n")
            spf_file.write("; ---------------------------------------------------\n")

        spf_file.write(f"M17\n")

    # Define the file path for the text file with selected parameter sets
    selected_params_file_path = os.path.join(folder_path, "selected_param_sets.txt")

    # Save the currently selected parameter sets in a .txt file
    with open(selected_params_file_path, "w") as param_file:
        param_file.write("Selected Parameter Sets:\n")
        for group_name, param_name in selected_params.items():
            # Extract the actual value from the tk.StringVar object using .get()
            param_file.write(f"{group_name}: {param_name.get()}\n")

    print(f"Configuration files saved in {folder_path}")

    if filetransfer:
        _transfer_to_sinumerik(filename, folder_path)
    else:
        os.startfile(folder_path)

    return folder_path



def gen_cfg_inlay(folder_output, input_vars, selected_params, filetransfer=False):
    filename = "CFG_INL.SPF"

    # Get the current timestamp for folder name (format: YYMMDD_HHmmSS)
    timestamp = time.strftime("%y%m%d_%H%M%S")
    folder_path = os.path.join(folder_output, f"{timestamp}")

    # Create the folder with the timestamp
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    # Define the file path for the SPF configuration file
    spf_file_path = os.path.join(folder_path, filename)
    xlsx_path = "_cfg_inlay_PUTx.xlsx"

    # Extract grid parameters
    x_num = int(input_vars['inlay']['INL_X_NUM'].get())  # Number of columns
    y_num = int(input_vars['inlay']['INL_Y_NUM'].get())  # Number of rows
    x_offset = float(input_vars['inlay']['INL_X_OFFSET'].get())  # X offset
    y_offset = float(input_vars['inlay']['INL_Y_OFFSET'].get())  # Y offset

    # Check if Excel file exists, if not create it with 'x' values
    if not os.path.exists(xlsx_path):
        df = pd.DataFrame("x", index=range(x_num), columns=range(y_num))
        df.to_excel(xlsx_path, index=False, header=False)

    # Load Excel file
    df = pd.read_excel(xlsx_path, header=None, dtype=str).fillna("")
    df = df.reindex(range(x_num), fill_value=0).reindex(columns=range(y_num), fill_value=0)
    df = df.map(lambda x: 1 if str(x).strip().lower() == "x" else 0)

    # Generate the SPF file content
    with open(spf_file_path, "w") as spf_file:
        spf_file.write(f"; CFG FILE FOR DMU50 AUTOMATION\n")
        spf_file.write(f"; GENERATED: {timestamp}\n")
        spf_file.write("; ---------------------------------------------------\n")

        # Write WP_X[i] and WP_Y[i] values
        cnt = 0
        for j in range(y_num):  # Rows
            for i in range(x_num):  # Columns
                if df.iloc[i, j] == 1:  # Consider only marked positions
                    spf_file.write(f"WP_X[{cnt}]={x_offset * i}\n")
                    spf_file.write(f"WP_Y[{cnt}]={y_offset * j}\n")
                    cnt += 1
        spf_file.write(f"WP_NUM={cnt}\n")
        spf_file.write("; ---------------------------------------------------\n")
        spf_file.write(f"M17\n")

    print(f"Configuration file saved at: {spf_file_path}")

    if filetransfer:
        _transfer_to_sinumerik(filename, folder_path)
    else:
        os.startfile(folder_path)



def _transfer_to_sinumerik(filename, folder_path):
    filename2 = f"_N_{filename.replace('.', '_')}"
    spf_file_path = os.path.join(folder_path, filename)
    spf_file_path2 = os.path.join(folder_path, filename2)
    shutil.copyfile(spf_file_path, spf_file_path2)

    # Transfer to Sinumerik
    url2 = "192.168.214.1"
    ssh_username = "manufact"
    ssh_password = "SUNRISE"
    upload_folder_nc = "/nckfs/_N_MPF_DIR/_N_AUTO_ROB_DIR"
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(url2, username=ssh_username, password=ssh_password)
    sftp = ssh.open_sftp()
    sftp.chdir(upload_folder_nc)
    if filename2 in sftp.listdir():
        sftp.remove(filename2)
    sftp.put(spf_file_path2, filename2)
    sftp.close()
    ssh.close()
    os.remove(spf_file_path2)

    print(f"------->>>> {filename} TRANSFERED TO SINUMERIK ------->>>> ")

