import matplotlib.pyplot as plt
from functions import *


def generate_picture_clp(all_group_vars, picture_path, DEBUG=False):
    vars = all_group_vars['clp']
    CLP_BACKENWEITE, CLP_BACKENHOHE, CLP_SPANNHOHE, CLP_AUFLAGETIEFE,MESSPOS_Z = (float(vars[k]) for k in
                                                                        ['CLP_BACKENWEITE', 'CLP_BACKENHOHE',
                                                                         'CLP_SPANNHOHE', 'CLP_AUFLAGETIEFE',
                                                                         'MESSPOS_Z'])

    try:
        WPR_X, WPR_Y, WPR_Z = (
            float(all_group_vars['wp'][k]) for k in ['WPR_X', 'WPR_Y', 'WPR_Z']
        )
    except (KeyError, ValueError):
        WPR_X = CLP_BACKENWEITE/2
        WPR_Y = CLP_BACKENWEITE/2
        WPR_Z = CLP_BACKENWEITE

    if min(WPR_X, WPR_Y, WPR_Z) <= 0:
        raise ValueError("Dimensions must be positive.")

    fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

    # Define raw workpiece dimensions
    x_cube, y_cube, z_cube = WPR_X,WPR_Y, WPR_Z
    vertices_raw = np.array([[0, 0, 0], [x_cube, 0, 0], [x_cube, y_cube, 0], [0, y_cube, 0],
                             [0, 0, WPR_Z], [x_cube, 0, WPR_Z], [x_cube, y_cube, WPR_Z], [0, y_cube, WPR_Z]])
    faces_raw = [vertices_raw[[0, 1, 2, 3]], vertices_raw[[4, 5, 6, 7]], vertices_raw[[0, 3, 7, 4]],
                 vertices_raw[[1, 2, 6, 5]], vertices_raw[[0, 1, 5, 4]], vertices_raw[[2, 3, 7, 6]]]

    # Set axis properties
    ax.set_box_aspect([x_cube, y_cube, z_cube])
    ax.set(xticks=[], yticks=[], zticks=[])

    # Draw WP coordinate system
    axis_len = max(x_cube, y_cube, z_cube) * 0.2
    colors = ['r', 'g', 'b']
    origin_x = 0
    origin_y = 0
    origin_z = 0
    for i, vec in enumerate(np.eye(3)):
        ax.quiver(origin_x, origin_y, origin_z, *(axis_len * vec), color=colors[i], linewidth=3)
    ax.text(origin_x, origin_y, origin_z - axis_len * 0.3, 'WP', color='black', fontsize=9, weight='bold', ha='center',
            va='top')

    # Draw WP
    ax.add_collection3d(Poly3DCollection(faces_raw, facecolors='k', linewidths=1, edgecolors='k', alpha=.15))

    # Draw CLP coordinate system
    axis_len = max(x_cube, y_cube, z_cube) * 0.15
    colors = ['r', 'g', 'b']
    origin_x = WPR_X/2
    origin_y = WPR_Y/2
    origin_z = 0
    for i, vec in enumerate(np.eye(3)):
        ax.quiver(origin_x, origin_y, origin_z, *(axis_len * vec), color=colors[i], linewidth=3)
    ax.text(origin_x, origin_y, origin_z - axis_len * 0.3, 'CLP', color='blue', fontsize=9, weight='bold', ha='center',
            va='top')

    # Define clamping block dimensions
    clp_deep = MESSPOS_Z
    base_x = WPR_X/2 - CLP_BACKENWEITE / 2
    alpha = 0.35
    color = 'blue'
    linewidth = 1

    # Draw clamping blocks
    x = base_x
    dx = CLP_BACKENWEITE
    y = 0
    dy1 = clp_deep
    dy2 = CLP_AUFLAGETIEFE
    z = 0
    dz1 = CLP_SPANNHOHE
    dz2 = CLP_BACKENHOHE
    plot_clamping(ax, x, y, z, dx, dy1, dy2, dz1, dz2, color=color,
                  alpha=alpha, linewidth=linewidth)
    y = y_cube
    plot_clamping(ax, x, y, z, dx, dy1, dy2, dz1, dz2, color=color,
                  alpha=alpha, linewidth=linewidth, inverty=True)

    # Draw text for geometry values
    ax.text(0, WPR_Y+clp_deep, CLP_SPANNHOHE/2, f'{CLP_SPANNHOHE}mm', color='blue', fontsize=9, weight='bold', ha='right', va='center')
    ax.text(0, WPR_Y+clp_deep, -CLP_BACKENHOHE/2, f'{CLP_BACKENHOHE}mm', color='blue', fontsize=9, weight='bold', ha='right', va='center')
    ax.text(WPR_X, WPR_Y+clp_deep, CLP_SPANNHOHE, f'{CLP_BACKENWEITE}mm', color='blue', fontsize=9, weight='bold', ha='right', va='center')
    ax.text(WPR_X, WPR_Y-CLP_AUFLAGETIEFE/2, 0, f'{CLP_AUFLAGETIEFE}mm', color='blue', fontsize=9, weight='bold', ha='left', va='bottom')

    # Set view properties
    z_trans = WPR_Z*0.3
    zoom_factor = 1.35  # Adjust this factor to zoom out more or less
    ax.view_init(elev=30, azim=-160)
    ax.set_xlim([-x_cube * zoom_factor * 0.1, x_cube * zoom_factor])
    ax.set_ylim([-y_cube * zoom_factor * 0.1, y_cube * zoom_factor])
    ax.set_zlim([-WPR_Z * zoom_factor * 0.1 - z_trans, WPR_Z * zoom_factor - z_trans])
    ax.set_aspect('auto')
    ax.grid(False)  # Remove grid lines
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
    for axis in [ax.xaxis, ax.yaxis, ax.zaxis]:
        axis.set_pane_color((1, 1, 1, 0))  # Hide background panes
        axis.line.set_color((1, 1, 1, 0))  # Hide axis lines

    # Save or display the plot
    if not DEBUG:
        fig.savefig(picture_path, bbox_inches='tight', dpi=300, transparent=True)
    else:
        plt.show()
    plt.close()


# Example use-case
if __name__ == "__main__":
    all_group_vars = {
        'CLP_BACKENWEITE': 25,
        'CLP_BACKENHOHE': 20,
        'CLP_SPANNHOHE': 3,
        'CLP_AUFLAGETIEFE': 3
    }
    generate_picture_clp({'clp': all_group_vars}, "cfg_picture/TEST_wpraw.jpg", DEBUG=True)