
from typing import Tuple, Union

import numbers

from geogst.core.geometries.planes import *

from ..apps.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[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

        result, err = qgis_project_coords(
            x=source_point_longitude,
            y=source_point_latitude,
            dest_crs=dest_crs,
        )

        if err:
            return None, err

        dest_crs_src_pt_x, dest_crs_src_pt_y = result

        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(),
        )
