#!/usr/bin/env python3

import datetime
import dateutil.parser

from debian import changelog
from casacore import tables
 
output_path = "Sources"

with open('icrf2.dat') as input_file:
    lines = input_file.readlines()

with open('debian/changelog') as cl_file:
    cl = changelog.Changelog(cl_file)

# Create data table
columns = [
    tables.makescacoldesc('MJD', 0., valuetype='double',
                          keywords={'UNIT':'d'}),
    tables.makescacoldesc('Name', '', valuetype='string'),
    tables.makescacoldesc('Type', '', valuetype='string'),
    tables.makescacoldesc('Long', 0., valuetype='double',
                          keywords={'UNIT':'deg'}),
    tables.makescacoldesc('Lat', 0., valuetype='double',
                          keywords={'UNIT':'deg'}),
    tables.makescacoldesc('Source', '', valuetype='string'),
    tables.makescacoldesc('Comment', '', valuetype='string'),
]

with tables.table('Sources', tables.tablecreatedesc(columns), len(lines)) as tbl:
    tbl.putinfo({'type': 'IERS', 'subType': 'source'})
    tbl.putkeywords({
        'MJD0': 0,
        'dMJD': 0.0,
        'VS_VERSION': '{:04d}.{:04.0f}'.format(int(cl.upstream_version),
                                               float(cl.debian_version)),
        'VS_CREATE': dateutil.parser.parse(cl.date).strftime('%Y/%m/%d/%H:%M'),
        'VS_DATE': dateutil.parser.parse(cl.date).strftime('%Y/%m/%d/%H:%M'),
        'VS_TYPE': 'List of Source positions'
    })

    tablerows = tbl.row()
    for i, row in enumerate(lines):
        [[lon, lat ]] =  tables.taql("calc meas.dir('J2000',[{}h{}m{},{}d{}m{}]) deg"
                                     .format(row[37:39], row[40:42], row[43:54],
                                             row[55:58], row[59:61], row[62:72]))
        tablerows.put(i, {
            'MJD': 0.0,
            'Name': str(row[:16]),
            'Type': 'ICRS',
            'Long': lon,
            'Lat':  lat,
            'Source': 'ICRF2'
        })
