from astropy.io import fits
import sys, math

from astropy_healpix import HEALPix
from astropy.coordinates import SkyCoord  # High-level coordinates
from astropy.coordinates import ICRS, Galactic, FK4, FK5  # Low-level frames
from astropy.coordinates import Angle, Latitude, Longitude  # Angles
import astropy.units as u

from coma.config import *

def load_erass1_fits(filename, names=False):
    
    cen_crd = SkyCoord(ra_cen, de_cen, frame=FK5(), unit="deg")
    rmax=7.0 # deg
    
    #filename="erass1-m.fits.gz"

    if(names==True):
        fout=filename.replace(".fits.gz", ".names.reg")
    else:
        fout=filename.replace(".fits.gz", ".reg")

    with open("./{}".format(fout), 'w') as writer:
        with fits.open(filename, memmap=True) as hdul:
            hdul.info()
    
            data   = hdul[1].data
            header = hdul[1].header
            cols   = hdul[1].columns



            print(cols)
            #sys.exit()
            for r in data:
                #IdCluster = int(r['IdCluster'])
                #UID = int(r['UId'])
                #UIDhard = int(r['UIdHard'])
                #RADEC_ERR = float(r['RADEErr'])
                #EXT = float(r['EXT'])
                #s_EXT = r['s_EXT']
                #EXT_LIKE = r['EXTLike']
                #DET_LIKE = r['DetLike0']
                #ML_CTS = r['MLcts1']
                #s_ML_CTS = r['s_MLcts1']
                #ML_RATE = r['MLRate1']
                #s_ML_RATE = r['s_MLRate1']
                #ML_FLUX = r['MLFlux1']
                #s_ML_FLUX = r['s_MLFlux1']
                #ML_EXP = r['MLExp1']
                name=r['IAUName']
                poserr=float(r['posErr']) # 1-sigma positional uncertainty
                ra=float(r['RAdeg'])
                dec=float(r['DEdeg'])

                P=0.98
                koeff=math.sqrt(-2*math.log(1-P))
            
                crd = SkyCoord(ra, dec, frame=FK5(), unit="deg")
                sep=crd.separation(cen_crd).deg
                if(sep < rmax):
                    print(ra,dec,sep)
                    if(names==True):
                        writer.write("fk5;circle({}, {}, {}) # text={{{}}}\n".format(ra,dec,poserr/60/60, name))
                    else:
                        writer.write("fk5;circle({}, {}, {})\n".format(ra,dec,poserr/60/60))

load_erass1_fits("erass1-m.fits.gz")
load_erass1_fits("erass1-s.fits.gz")
load_erass1_fits("erass1-h.fits.gz")

load_erass1_fits("erass1-m.fits.gz", names=True)
load_erass1_fits("erass1-s.fits.gz", names=True)
load_erass1_fits("erass1-h.fits.gz", names=True)



"""        
#filename='4XMM_DR12cat_slim_v1.0_UDS.fits.catalog'
filename='4XMM_slim_DR14cat_v1.0_Coma.fits'
fout=filename.replace(".fits", ".names.reg")

hdul = fits.open(filename)
#hdul.info()

tbdata = hdul[1].data
hdul.close()


with open("./{}".format(fout), 'w') as writer:
    for rec in tbdata:
        print("fk5;circle({}, {}, 0.008)".format(rec['sc_ra'],rec['sc_dec']))
        writer.write("fk5;circle({}, {}, {}) # text={{{}}}\n".format(rec['sc_ra'],rec['sc_dec'],rec['sc_poserr']/3600,rec['IAUNAME']))

"""
