# Path: gammasky/utils.py
# def table_to_list_of_dict(table):
#     """Convert table to list of dict."""
#     rows = []
#     for row in table:
#         data = OrderedDict()
#         for name in table.colnames:
#             val = row[name]
#             # TODO: The below is not working, find a fix
#             # if val in {np.nan}:
#             #     val = None
#             if isinstance(val, np.int64):
#                 val = int(val)
#             elif isinstance(val, np.int32):
#                 val = int(val)
#             elif isinstance(val, np.bool_):
#                 val = bool(val)
#             elif isinstance(val, np.float):
#                 val = float(val)
#             elif isinstance(val, np.float32):
#                 val = float(val)
#             elif isinstance(val, np.str):
#                 val = str(val)
#             elif isinstance(val, np.ndarray):
#                 vals = [float(_) for _ in val]
#                 val = list(vals)
#             else:
#                 raise ValueError('Unknown type: {} {}'.format(val, type(val)))
#             data[name] = val
# 
#         rows.append(data)
# 
#     return rows
# 
# def dump_to_json(data, path):
#     # Replace all instances of NaN and Inf values (which are not valid JSON) with null
#     text = json.dumps(data)
#     text = text.replace('NaN', 'null').replace('-Infinity', 'null').replace('Infinity', 'null')
#     data = json.loads(text)
# 
#     with path.open('w') as fh:
#         json.dump(data, fh)
# 
# def get_selected_sources(cat, sources):
#     if sources == 'all':
#         return list(range(len(cat.table)))
#     else:
#         return [int(_) for _ in sources.split(',')]
# 
# Path: gammasky/config.py
# DATA_DIR = Path('src/data/')


from pathlib import Path
from astropy.table import Table
from gammapy.catalog import SourceCatalog3FHL, SourceCatalogGammaCat, SourceCatalog3FGL
from .utils import table_to_list_of_dict, dump_to_json, get_selected_sources
from .config import DATA_DIR
import click
import numpy as np
import json
        click.secho('Writing: {}'.format(filename), fg='green')
        dump_to_json(data, filename)


def make_tev_catalog_data():
    click.secho('Making TeV catalog data (from gamma-cat)...', fg='green')

    out_dir = DATA_DIR / 'cat/tev'
    out_dir.mkdir(parents=True, exist_ok=True)

    cat = SourceCatalogGammaCat(filename='input_data/gammacat.fits.gz')
    cols = ['source_id', 'common_name', 'ra', 'dec', 'glon', 'glat',
            'gamma_names', 'fermi_names', 'other_names', 'classes']
    cat.table = cat.table[cols]
    data = cat._data_python_list

    filename = out_dir / 'cat.json'
    click.secho('Writing tev {}'.format(filename), fg='green')
    dump_to_json(data, filename)


def make_tev_source_data(sources):
    click.secho('Making source data from TeV catalog...', fg='green')

    cat = SourceCatalogGammaCat(filename='input_data/gammacat.fits.gz')
    sources = get_selected_sources(cat, sources)
    for idx in sources:
        source = cat[idx]
        data = source._data_python_dict


# Path: gammasky/utils.py
# def table_to_list_of_dict(table):
#     """Convert table to list of dict."""
#     rows = []
#     for row in table:
#         data = OrderedDict()
#         for name in table.colnames:
#             val = row[name]
#             # TODO: The below is not working, find a fix
#             # if val in {np.nan}:
#             #     val = None
#             if isinstance(val, np.int64):
#                 val = int(val)
#             elif isinstance(val, np.int32):
#                 val = int(val)
#             elif isinstance(val, np.bool_):
#                 val = bool(val)
#             elif isinstance(val, np.float):
#                 val = float(val)
#             elif isinstance(val, np.float32):
#                 val = float(val)
#             elif isinstance(val, np.str):
#                 val = str(val)
#             elif isinstance(val, np.ndarray):
#                 vals = [float(_) for _ in val]
#                 val = list(vals)
#             else:
#                 raise ValueError('Unknown type: {} {}'.format(val, type(val)))
#             data[name] = val
# 
#         rows.append(data)
# 
#     return rows
# 
# def dump_to_json(data, path):
#     # Replace all instances of NaN and Inf values (which are not valid JSON) with null
#     text = json.dumps(data)
#     text = text.replace('NaN', 'null').replace('-Infinity', 'null').replace('Infinity', 'null')
#     data = json.loads(text)
# 
#     with path.open('w') as fh:
#         json.dump(data, fh)
# 
# def get_selected_sources(cat, sources):
#     if sources == 'all':
#         return list(range(len(cat.table)))
#     else:
#         return [int(_) for _ in sources.split(',')]
# 
# Path: gammasky/config.py
# DATA_DIR = Path('src/data/')


# Path: gammasky/catalogs.py
from pathlib import Path
from astropy.table import Table
from gammapy.catalog import SourceCatalog3FHL, SourceCatalogGammaCat, SourceCatalog3FGL
from .utils import table_to_list_of_dict, dump_to_json, get_selected_sources
from .config import DATA_DIR
import click
import numpy as np
import json

        click.secho('Writing: {}'.format(filename), fg='green')
        dump_to_json(data, filename)


def make_tev_catalog_data():
    click.secho('Making TeV catalog data (from gamma-cat)...', fg='green')

    out_dir = DATA_DIR / 'cat/tev'
    out_dir.mkdir(parents=True, exist_ok=True)

    cat = SourceCatalogGammaCat(filename='input_data/gammacat.fits.gz')
    cols = ['source_id', 'common_name', 'ra', 'dec', 'glon', 'glat',
            'gamma_names', 'fermi_names', 'other_names', 'classes']
    cat.table = cat.table[cols]
    data = cat._data_python_list

    filename = out_dir / 'cat.json'
    click.secho('Writing tev {}'.format(filename), fg='green')
    dump_to_json(data, filename)


def make_tev_source_data(sources):
    click.secho('Making source data from TeV catalog...', fg='green')

    cat = SourceCatalogGammaCat(filename='input_data/gammacat.fits.gz')
    sources = get_selected_sources(cat, sources)
    for idx in sources:
        source = cat[idx]
        data = source._data_python_dict


        out_dir = DATA_DIR / 'cat/tev/sources/{:04d}'.format(data['source_id'])