"""Conversion between Ordnance Survey National Grid coordinates and latitude
and longitude, following the Ordnance Survey's "A Guide to Coordinate Systems
in Great Britain".

The latitude and longitude are on the OSGB36 datum (the Airy 1830 ellipsoid),
not on the WGS84 datum used by most GPS devices: positions in the two differ by
between about 60 and 140 m across Great Britain, and this module does not
transform between them.
"""

import math

# The Airy 1830 ellipsoid: semi-major axis, a, and semi-minor axis, b (m).
a, b = 6377563.396, 6356256.909
e2 = (a**2 - b**2) / a**2  # the square of the eccentricity
n = (a - b) / (a + b)

# The National Grid's transverse Mercator projection: the grid coordinates,
# (E0, N0), of the true origin, at latitude phi0 and longitude lambda0, and the
# scale factor on the central meridian, F0.
E0, N0 = 400000, -100000
phi0, lambda0 = math.radians(49), math.radians(-2)
F0 = 0.9996012717

# The letters of the grid squares, in rows from north to south (there is no I).
LETTERS = "ABCDEFGHJKLMNOPQRSTUVWXYZ"


def f_M(phi):
    """The distance along the central meridian, scaled by F0, from latitude
    phi0 to latitude phi (in radians)."""
    dphi, sphi = phi - phi0, phi + phi0
    return b * F0 * (
        (1 + n + 5 / 4 * n**2 + 5 / 4 * n**3) * dphi
        - (3 * n + 3 * n**2 + 21 / 8 * n**3) * math.sin(dphi) * math.cos(sphi)
        + (15 / 8 * n**2 + 15 / 8 * n**3)
        * math.sin(2 * dphi) * math.cos(2 * sphi)
        - 35 / 24 * n**3 * math.sin(3 * dphi) * math.cos(3 * sphi)
    )


def radii(phi):
    """The radii of curvature of the ellipsoid at latitude phi, in the prime
    vertical (nu) and along the meridian (rho), each scaled by F0, and
    eta2 = nu/rho - 1."""
    s = 1 - e2 * math.sin(phi) ** 2
    nu = a * F0 / math.sqrt(s)
    rho = a * F0 * (1 - e2) / s**1.5
    return nu, rho, nu / rho - 1


def os_to_ll(E, N):
    """Convert grid coordinates (E, N), in metres, to latitude and longitude,
    in degrees."""
    # phi' is the latitude of the point on the central meridian with northing
    # N: find it by inverting f_M iteratively.
    phip, M = phi0, 0
    while abs(N - N0 - M) >= 1e-5:
        phip += (N - N0 - M) / (a * F0)
        M = f_M(phip)

    nu, rho, eta2 = radii(phip)
    t = math.tan(phip)
    sec = 1 / math.cos(phip)
    c1 = t / (2 * rho * nu)
    c2 = t / (24 * rho * nu**3) * (5 + 3 * t**2 + eta2 - 9 * eta2 * t**2)
    c3 = t / (720 * rho * nu**5) * (61 + 90 * t**2 + 45 * t**4)
    d1 = sec / nu
    d2 = sec / (6 * nu**3) * (nu / rho + 2 * t**2)
    d3 = sec / (120 * nu**5) * (5 + 28 * t**2 + 24 * t**4)
    d4 = sec / (5040 * nu**7) * (61 + 662 * t**2 + 1320 * t**4 + 720 * t**6)

    x = E - E0
    phi = phip - c1 * x**2 + c2 * x**4 - c3 * x**6
    lam = lambda0 + d1 * x - d2 * x**3 + d3 * x**5 - d4 * x**7
    return math.degrees(phi), math.degrees(lam)


def ll_to_os(phi, lam):
    """Convert latitude and longitude, in degrees, to grid coordinates (E, N),
    in metres."""
    phi, lam = math.radians(phi), math.radians(lam)
    nu, rho, eta2 = radii(phi)
    s, c, t = math.sin(phi), math.cos(phi), math.tan(phi)
    a1 = f_M(phi) + N0
    a2 = nu / 2 * s * c
    a3 = nu / 24 * s * c**3 * (5 - t**2 + 9 * eta2)
    a4 = nu / 720 * s * c**5 * (61 - 58 * t**2 + t**4)
    b1 = nu * c
    b2 = nu / 6 * c**3 * (nu / rho - t**2)
    b3 = nu / 120 * c**5 * (5 - 18 * t**2 + t**4 + 14 * eta2 - 58 * eta2 * t**2)

    x = lam - lambda0
    N = a1 + a2 * x**2 + a3 * x**4 + a4 * x**6
    E = E0 + b1 * x + b2 * x**3 + b3 * x**5
    return E, N


def to_grid_ref(E, N, digits=10):
    """The grid reference, with letters, of the square of the grid that
    contains the point (E, N): e.g. 'TL 44735 58334' (10 digits, a 1 m
    square) or 'TL 447 583' (6 digits, a 100 m square)."""
    E, N = int(E), int(N)
    # The first letter gives the square of side 500 km, counted from the one
    # whose south-west corner is the false origin, S; the second gives the
    # square of side 100 km within it.
    e500, n500 = E // 500000 + 2, N // 500000
    e100, n100 = E // 100000 % 5, N // 100000 % 5
    letters = LETTERS[(3 - n500) * 5 + e500] + LETTERS[(4 - n100) * 5 + e100]
    k = digits // 2
    scale = 10 ** (5 - k)
    return f"{letters} {E % 100000 // scale:0{k}d} {N % 100000 // scale:0{k}d}"


def from_grid_ref(ref):
    """The grid coordinates (E, N), in metres, of the south-west corner of the
    square given by a grid reference with letters, such as 'TL 447 583' (with
    or without the spaces)."""
    ref = ref.upper().replace(" ", "")
    letters, digits = ref[:2], ref[2:]
    k = len(digits) // 2
    i, j = LETTERS.index(letters[0]), LETTERS.index(letters[1])
    E = (i % 5 - 2) * 500000 + j % 5 * 100000
    N = (3 - i // 5) * 500000 + (4 - j // 5) * 100000
    if k == 0:  # the letters alone: the square of side 100 km
        return E, N
    scale = 10 ** (5 - k)
    return E + int(digits[:k]) * scale, N + int(digits[k:]) * scale


def deg_to_dms(deg, ndp=4):
    """Convert an angle in decimal degrees to (sign, degrees, minutes,
    seconds), with the seconds rounded to ndp decimal places. The sign, +1 or
    -1, applies to the whole angle: -0.5 degrees is (-1, 0, 30, 0.0)."""
    sign = -1 if deg < 0 else 1
    # Round the seconds before dividing, so that they never round up to 60.
    m, s = divmod(round(abs(deg) * 3600, ndp), 60)
    d, m = divmod(m, 60)
    return sign, int(d), int(m), s


def dms_to_deg(d, m, s, hemisphere="N"):
    """Convert an angle in degrees, minutes and seconds in the hemisphere 'N',
    'S', 'E' or 'W' to decimal degrees, negative to the south and west."""
    sign = -1 if hemisphere.upper() in "SW" else 1
    return sign * (d + m / 60 + s / 3600)


def format_dms(deg, coordinate, ndp=4):
    """Format a latitude or longitude (coordinate is 'latitude' or
    'longitude') in decimal degrees as, e.g., 52° 12′ 13.6826″ N."""
    sign, d, m, s = deg_to_dms(deg, ndp)
    hemisphere = {"latitude": "NS", "longitude": "EW"}[coordinate][sign < 0]
    return f"{d}° {m}′ {s:.{ndp}f}″ {hemisphere}"
