
from typing import Tuple, Union

import numbers

from gst.core.geometries.planes import *
from gst.qgis.orientations import *


def reorient_plane_and_source_point(
    source_point_longitude: numbers.Real,
    source_point_latitude: numbers.Real,
    source_point_elevation: numbers.Real,
    dip_direction_as_north_azimuth: numbers.Real,
    source_dip_angle: numbers.Real,
    dest_crs: 'QGIS_CRS',
) -> Tuple[Union[type(None), Tuple[Plane, Point]], Error]:

    try:

        # Correct dip direction and angle by destination crs

        dest_crs_plane_orientation, err = convert_plane_orientation_to_crs(
            dip_direction_as_north_azimuth=dip_direction_as_north_azimuth,
            source_dip_angle=source_dip_angle,
            local_pt_longitude=source_point_longitude,
            local_pt_latitude=source_point_latitude,
            dest_crs=dest_crs,
        )

        if err:
            return None, err

        dest_crs_src_pt_x, dest_crs_src_pt_y = qgs_project_xy(
            x=source_point_longitude,
            y=source_point_latitude,
            dest_crs=dest_crs,
        )

        dest_crs_src_pt_3d = Point(
            dest_crs_src_pt_x,
            dest_crs_src_pt_y,
            source_point_elevation,
        )

        return (
            dest_crs_plane_orientation,
            dest_crs_src_pt_3d
        ), Error()

    except Exception as e:

        return None, Error(
            True,
            caller_name(),
            e,
            traceback.format_exc(),
        )
