#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# System modules
from astropy.coordinates import SkyCoord, EarthLocation
from astropy.coordinates.name_resolve import NameResolveError
from astropy.time import Time
from astropy.io import fits

# Custom modules
from utils.logger import log
from config.constants import lon, lat, alt
from config.constants import pixscale, temp_fits

# Conversion to radec


def to_radec(string):
    try:
        coor = SkyCoord(string,
                        unit=("hourangle", "deg"),
                        equinox=Time.now())

        return [coor.ra.hourangle, coor.dec.degree]

    except ValueError as e:
        log.warning(f"Cannot resolve coordinates, trying with name")
        log.warning(e)
        try:
            coor = SkyCoord.from_name(string)
            log.info(f"Found catalog name")
            return [coor.ra.hourangle, coor.dec.degree]
        except NameResolveError as e:
            log.error(f"Cannot resolve name")
            log.error(e)
            return


def calculate_offset(string="13 56 44  +27 28 01", image=temp_fits):

    header = fits.getheader(image)

    location = EarthLocation(lat=lat, lon=lon, height=alt)

    obstime = Time(header["date-obs"])

    RA = header["ra"]
    DEC = header["dec"]
    coor_center = SkyCoord(ra=RA, dec=DEC,
                           unit=("deg", "deg"),
                           equinox=obstime,
                           obstime=obstime,
                           location=location)

    coor_star = SkyCoord(string,
                         unit=("hourangle", "deg"),
                         equinox=obstime,
                         obstime=obstime,
                         location=location)

    #trans = coor_star.transform_to(coor_center.skyoffset_frame())

    dalt = coor_center.altaz.alt - coor_star.altaz.alt
    daz = coor_center.altaz.az - coor_star.altaz.az

    return [dalt.deg, -daz.deg]
