#!/usr/bin/python
# coding: utf-8

# Stellarium Web Engine - Copyright (c) 2018 - Noctua Software Ltd
#
# This program is licensed under the terms of the GNU AGPL v3, or
# alternatively under a commercial licence.
#
# The terms of the AGPL v3 license can be found in the main directory of this
# repository.

# Generate the file hip.inl, that contains a mapping of HIP -> healpix for
# fast HIP stars lookup.

from math import *

import csv
import healpy
import sys

sys.path.append('./tools')
from utils import generator

@generator('hip.csv', md5='b0b86439386bbcbae15efc402ed06da7')
def get_hip_data_file(path):
    '''Get HIP data from gaia TAP server'''
    # We use the hipparcos new reduction table, as it is supposed to have
    # better values.
    from astroquery.gaia import Gaia
    QUERY = '''
        SELECT hip, ra, dec, hp_mag AS vmag
        FROM public.hipparcos_newreduction
        ORDER BY hip
    '''
    job = Gaia.launch_job_async(QUERY)
    r = job.get_results()
    r.write(path, overwrite=True, format='ascii.csv')
    if not hasattr(job, 'get_jobid'):
        print 'Warning: cannot delete Gaia job'
        return
    Gaia.remove_jobs([job.get_jobid()])

def run():
    data = list(csv.DictReader(open(get_hip_data_file())))
    htable = {}

    for d in data:
        ra = float(d['ra'])
        de = float(d['dec'])
        pix = healpy.ang2pix(4, ra, de, nest=True, lonlat=True)
        htable[int(d['hip'])] = pix
    data = [htable.get(x, 255) for x in range(max(htable.keys()))]

    out = open('src/hip.inl', 'w')
    print >>out, '// HIP -> pix pos at order 2.'
    print >>out, '// Generated by tools/make-hip.py'

    for i, v in enumerate(data):
        print >>out, '%3d,' % v,
        if (i + 1) % 15 == 0: print >>out

if __name__ == '__main__':
    run()
