from TemmaSerial import TemmaSerial

from datetime import datetime
import astropy
from astropy.time import Time
from astropy import coordinates as coords
#from astropy import units as u

def set_site_info(config, mount):
    siteconfig = config['site']
    site_name = siteconfig['name']
    site_long = siteconfig['longitude']
    site_lat = siteconfig['latitude']
    siteloc=coords.EarthLocation(lon=config['site']['longitude'], lat=config['site']['latitude'])
    lat_d, lat_m, lat_s = siteloc.latitude.dms
    # # --- Temma format : +48:05:30 -> +48055
    if lat_d>0:
        temma_lat_format = "%+2d%02d%01d"%(lat_d,lat_m,int(lat_s/6.))
    else:
        temma_lat_format = "%2d%02d%01d"%(lat_d,-lat_m,int(-lat_s/6.))
    print(("setting temma latitude to : ", temma_lat_format))
    mount.set_latitude(temma_lat_format)
    return site_name, siteloc

def calcLST(longi_deci):
    gmt = datetime.utcnow() #GMT time in UTC
    now = Time(gmt)
    try:
        lst = now.sidereal_time('apparent', longi_deci)
    except astropy.utils.iers.IERSRangeError:
        from astropy.utils.iers import IERS_A, IERS_A_URL
        if os.path.exists(os.path.basename(IERS_A_URL)):
            iers_a = IERS_A.open(os.path.basename(IERS_A_URL))
        else:
            iers_a = IERS_A.open(IERS_A_URL)
        now.delta_ut1_utc = now.get_delta_ut1_utc(iers_a)
        #validated with http://www.jgiesen.de/astro/astroJS/siderealClock/
        lst = now.sidereal_time('apparent', longitude=longi_deci)
    return gmt, lst

if __name__=="__main__":
    import yaml, os, sys
    #will add arg options later...
    configfile="stardice.yml"
    config=yaml.load(open(configfile))
    print("yaml configuration:")
    print(config)

    #1 start the temma and check connection
    s="Checking serial port presence: "
    if os.path.exists(config['temma']['port']):
        print((s+"OK"))
    else:
        print((s+"%s not found! exiting..."%config['temma']['port']))
        sys.exit(1)
    temma = TemmaSerial(config)
    if temma is None:
        print('temma mount failed connection, exiting...')
        sys.exit(1)
        
    #2 upload site information
    site_name, site_loc = set_site_info(config, temma)
    rsp =  temma.get_correction_speed()
    #"N" or "S" but we already know that from site latitude
    hemisphere = rsp[7]
    # RA/DEC follow speed (slow tunable speed set to 90%/90% of sidereal angular speed at switch on.
    RA_ns_val= rsp[2:4]
    DEC_ns_val= rsp[5:7]
    #The East/West telescope needs to be defined
    res = temma.get_radec()
    print(res)
    
    #3 compute and upload LST
    longi_deci = site_loc.longitude.hour
    gmt, lst = calcLST(longi_deci)
    print((gmt, lst))
    print("Upload LST to Temma...")
    lst_h, lst_m, lst_s = lst.hms
    temma_lst_format = "%02u%02u%02u"%(lst_h,lst_m,lst_s)
    temma.set_LST(temma_lst_format)
    print((temma.get_LST()))

    #3bis one can compute polaris position approximately
    year = gmt.year
    adpolaire=(0.01875*year)-34.9574#decimal hour
    polaris_angle = lst - adpolaire*astropy.units.hourangle
    #lst should be already in hourangle
    print(('Polaris angular position : ', polaris_angle))
    
    #4 move to a target in the sky!
    star_name="Landolt 92 245"
    star_coord = coords.SkyCoord('00h54m16s','+00d39m51s')
    d,m,s=star_coord.dec.dms
    if d>=0:
        dec_temma = "%02d%02d%01d"%(d,m,s/6.)
    else:
        dec_temma = "-%02d%02d%01d"%(abs(d),m,s/6.)
    h,m,s = star_coord.dec.hms
    ra_temma = "%02d%02d%02d"%(h, m,(s*1.666666667))#why in tenth of seconds?
    temma_fmt ="%s+%s"%(ra_temma,dec_temma)
    res, msg = temma.goto(temma_fmt)
    print((res, msg))
    
    print((temma.state_goto()))
    
