import matplotlib.pyplot as plt
from functions import *


def generate_picture_probe(all_group_vars, picture_path, DEBUG=False):

    (PRB_BOD_RE_Y, PRB_BOD_RE_X, PRB_BOD_LI_Y, PRB_BOD_LI_X,
     PRB_SEI_HI_Z, PRB_SEI_HI_X, PRB_SEI_VO_Z, PRB_SEI_VO_X,
     PRB_VERS_X_Y, PRB_VERS_X_Z) = \
        (float(all_group_vars['probe'][k]) for k in [
        'PRB_BOD_RE_Y', 'PRB_BOD_RE_X', 'PRB_BOD_LI_Y', 'PRB_BOD_LI_X',
        'PRB_SEI_HI_Z', 'PRB_SEI_HI_X', 'PRB_SEI_VO_Z', 'PRB_SEI_VO_X',
        'PRB_VERS_X_Y', 'PRB_VERS_X_Z'])

    try:
        CLP_BACKENWEITE, CLP_BACKENHOHE, CLP_SPANNHOHE, CLP_AUFLAGETIEFE, MESSPOSZ = (
            float(all_group_vars['clp'][k]) for k in
        ['CLP_BACKENWEITE', 'CLP_BACKENHOHE', 'CLP_SPANNHOHE', 'CLP_AUFLAGETIEFE','MESSPOS_Z']
        )
    except (KeyError, ValueError):
        CLP_BACKENWEITE = 100
        CLP_BACKENHOHE = 50
        CLP_SPANNHOHE = 5
        CLP_AUFLAGETIEFE = 5

    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

    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 = MESSPOSZ
    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 parameter
    def drawball(XXX, YYY, ZZZ, COLR, SCALFAC):
        u, v = np.mgrid[0:2 * np.pi:20j, 0:np.pi:20j]
        ball_radius = max(x_cube, y_cube, z_cube) * SCALFAC
        ax.plot_surface(
            XXX + ball_radius * np.cos(u) * np.sin(v),
            YYY + ball_radius * np.sin(u) * np.sin(v),
            ZZZ + ball_radius * np.cos(v),
            color=COLR
        )
    txt_offs = max(x_cube, y_cube, z_cube) * 0.05
    #BODEN
    boden_colr =  "red"
    drawball(x_cube-PRB_BOD_RE_X, WPR_Y/2+PRB_BOD_RE_Y, 0, boden_colr, 0.03)
    ax.text( x_cube-PRB_BOD_RE_X, WPR_Y/2+PRB_BOD_RE_Y, 0+txt_offs, f'PRB_BOD_RE', color=boden_colr, fontsize=7, weight='bold', ha='center', va='bottom')
    drawball(0+PRB_BOD_LI_X, WPR_Y/2+PRB_BOD_LI_Y*-1, 0, boden_colr, 0.03)
    ax.text( 0+PRB_BOD_LI_X, WPR_Y/2+PRB_BOD_LI_Y*-1, 0-txt_offs, f'PRB_BOD_LI', color=boden_colr, fontsize=7, weight='bold', ha='center', va='top')

    #SEITE
    seiten_colr =  "green"
    drawball(WPR_X/2+PRB_SEI_HI_X*-1, y_cube, PRB_SEI_HI_Z*-1, seiten_colr, 0.03)
    ax.text(WPR_X/2+PRB_SEI_HI_X*-1, y_cube, PRB_SEI_HI_Z*-1+txt_offs, f'PRB_SEI_HI', color=seiten_colr, fontsize=7, weight='bold', ha='right', va='bottom')
    drawball(WPR_X/2+PRB_SEI_VO_X, 0, PRB_SEI_VO_Z*-1, seiten_colr, 0.03)
    ax.text(WPR_X/2+PRB_SEI_VO_X, 0, PRB_SEI_VO_Z*-1+txt_offs, f'PRB_SEI_VO', color=seiten_colr, fontsize=7, weight='bold', ha='left', va='bottom')

    #VERSATZ Y
    vers_colr =  "blue"
    drawball(0, WPR_Y/2+PRB_VERS_X_Y*-1, PRB_VERS_X_Z*-1, vers_colr, 0.03)
    ax.text( 0, WPR_Y/2+PRB_VERS_X_Y*-1, PRB_VERS_X_Z+txt_offs, f'PRB_VERS_X', color=vers_colr, fontsize=7, weight='bold', ha='center', va='bottom')


    # Set view properties
    z_trans = WPR_Z*0.3
    zoom_factor = 1.2  # 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 = {
            'PRB_BOD_RE_Y': 0,
            'PRB_BOD_RE_X': 0,
            'PRB_BOD_LI_Y': 0,
            'PRB_BOD_LI_X': 0,
            'PRB_SEI_HI_X': 0,
            'PRB_SEI_HI_Z': 0,
            'PRB_SEI_VO_X': 0,
            'PRB_SEI_VO_Z': 0,
            'PRB_VERS_X_Y': 5.0,
            'PRB_VERS_X_Z': 2.5
    }
    generate_picture_probe({'probe': all_group_vars}, "cfg_picture/TEST_wpraw.jpg", DEBUG=True)
