#!/usr/bin/python3
""" By G.Landais (CDS)
    B/VSX
    aug-2022: get data from https://www.aavso.org/vsx/external/vsx_csv.dat.gz
    file built by Sebastrain Otero: sebastian@aavso.org

    usage: ./create.py [-h] [-c]  table_csv
       -c: check utf8 char
"""

from astropy.table import Table
import cdspyreadme
import sys
import getopt
import logging
import codecs
from datetime import datetime



#OID,Name,VarFlag,RAdeg,DEdeg,Type,LimitFlagOnMax,MagMax,MaxUncertaintyFlag,MaxPassband,MinIsAmplitude,LimitFlagOnMin,MagMin,MinUncertaintyFlag,MinPassband,Epoch,EpochUncertaintyFlag,LimitFlagOnPeriod,Period,PeriodUncertaintyFlag,SpectralType
desc = [
{"name":"OID"     , "fmt":"I8"  , "unit":None , "desc":"Internal identifier, can be used to link out to the VSX database (1)"},
{"name":"Name"    , "fmt":"A30" , "unit":None , "desc":"Variable star identifier"},
{"name":"V"       , "fmt":"I1"  , "unit":None , "desc":"Variability flag (2) (VarFlag)"},
{"name":"RAdeg"   , "fmt":"F9.5", "unit":"deg", "desc":"Right ascension (J2000)"},
{"name":"DEdeg"   , "fmt":"F9.5", "unit":"deg", "desc":"Declination (J2000)"},
{"name":"Type"    , "fmt":"A30" , "unit":None , "desc":"Variability type, ariability type, as in GCVS catalog Variability type (see details of VSX type list)"},
{"name":"l_max"   , "fmt":"A1"  , "unit":None , "desc":"Limit flag on max (LimitFlagOnMax)"},
{"name":"max"     , "fmt":None  , "unit":"mag", "desc":"Magnitude at maximum, or amplitude (MagMax)"},
{"name":"u_max"   , "fmt":None  , "unit":None , "desc":"Uncertainty flag on max (MaxUncertaintyFlag)"},
{"name":"n_max"   , "fmt":None  , "unit":None , "desc":"Passband on max magnitude (4) (MaxPassband)"},
{"name":"f_min"   , "fmt":None  , "unit":None , "desc":"Flag to indicate an amplitude (MinIsAmplitude)"},
{"name":"l_min"   , "fmt":None  , "unit":None , "desc":"Limit flag on min (LimitFlagOnMin)"},
{"name":"min"     , "fmt":None  , "unit":"mag", "desc":"Magnitude at minimum, or amplitude (MagMin)"},
{"name":"u_min"   , "fmt":None  , "unit":None , "desc":"Uncertainty flag on min (MinUncertaintyFlag)"},
{"name":"n_min"   , "fmt":None  , "unit":None , "desc":"Passband on min magnitude (MinPassband)"},
{"name":"Epoch"   , "fmt":None  , "unit":"d"  , "desc":"Epoch of maximum or minimum (HJD)"},
{"name":"u_Epoch" , "fmt":None  , "unit":None , "desc":"Uncertainty flag on epoch (EpochUncertaintyFlag)"},
{"name":"l_Period", "fmt":None  , "unit":None , "desc":"Limit flag on period (3) (LimitFlagOnPeriod)"},
{"name":"Period"  , "fmt":None  , "unit":"d"  , "desc":"Period of the variable in days"},
{"name":"u_Period", "fmt":None  , "unit":None , "desc":"Uncertainty flag on Period (3) (PeriodUncertaintyFlag)"},
{"name":"Sp"      , "fmt":None  , "unit":None , "desc":"Spectral type (SpectralType)"}
]


if __name__ == "__main__":
    __check = False

    try:
        __opts, __args = getopt.getopt(sys.argv[1:], "h", ["help"])
    except getopt.GetoptError as err:
        logging.error(err)
        sys.exit(r10)

    for __o, __a in __opts:
        if __o in ("-h", "--help"):
            help("__main__")
            sys.exit(0)

    __tablename = None
    for __a in __args:
        __tablename = __a
    if __tablename is None:
        help("__main__")
        sys.exit(0)

    sys.stderr.write("create .dat file from "+__tablename+"\n")
    day = datetime.now().strftime("%Y-%m-%d")

    tablemaker = cdspyreadme.CDSTablesMaker()
    astrotable=Table.read(__tablename, format="csv")
    table = tablemaker.addTable(astrotable, 
                                name="vsx.dat",
                                nullvalue="None", 
                                description=f"Variable Star indeX, Version {day}")


    columns = table.get_column(None)
    for i in range(len(desc)):
        cname = "col{}".format(i+1)
        if desc[i]["fmt"] != None:
            columns[i].set_format(desc[i]["fmt"])
        if desc[i]["name"] != None:
            columns[i].name = desc[i]["name"]
        if desc[i]["desc"] != None:
            columns[i].description = desc[i]["desc"]

    for i, col in enumerate(astrotable.columns):
        if desc[i]["unit"] != None:
            astrotable[col].unit = desc[i]["unit"]

    # create ASCII table
    tablemaker.writeCDSTables()

    # create ReadMe
    new_history = None
    try:
        with open("history", "r") as fd:
            history = fd.read()
        new_history = f"  * {day}: {table.nlines} stars, from http://www.aavso.org/vsx/"
        history += new_history
    except Exception as e:
        sys.stderr.write(f"****error get history file: {e}\n")
        sys.exit(1)

    tablemaker.setReadmeTemplate("ReadMe.template", {"history":history})
    with open("ReadMe.new", "w") as fd:
        tablemaker.makeReadMe(out=fd)

    try:
        with open("history", "a") as fout:
            fout.write(new_history+"\n")
    except Exception as e:
        sys.stderr.write(f"****error update history file: {e}\n")

