# -*- coding: utf-8 -*-
"""
Created on Wed Jan  4 14:00:00 2016

@author: cham
"""


import glob
import sys

import numpy as np
from astropy.io import fits
from astropy.table import Table, Column
from tqdm import trange


# scan fits header
def scan_fits_header(fps):
    cfn = sys._getframe().f_code.co_name
    for i in trange(len(fps), ncols=100, ascii=False, desc="**" + cfn + "**",
                    unit=" file"):
        fp = fps[i]
        #        print i, len(fps)
        # read fits
        hl = fits.open(fp)
        hdr_dict = dict(hl[0].header)
        # initiate table
        if i == 0:
            t = Table()
            for k, v in hdr_dict.items():
                #                print k, v
                if type(v) is str:
                    t.add_column(
                        Column(data=np.array([]), dtype=object, name=k))
                else:
                    t.add_column(
                        Column(data=np.array([]), dtype=type(v), name=k))
        # add rows
        t.add_row(hdr_dict.values())
    t.add_column(Column(fps, "fps"), 0)

    # fix column dtype
    for i, colname in enumerate(t.colnames):
        if t[colname].dtype == np.dtype("O"):
            newcol = t[colname].astype("str")
            t.remove_column(colname)
            t.add_column(newcol, i)

    return t


def scan_files(dirpath, xdriftcol=True):

    fps_all = glob.glob(dirpath+"/*.fits")
    fps_all.sort()
    t = scan_fits_header(fps_all)

    if xdriftcol:
        t.add_column(Column(np.zeros((len(t),), dtype=int) * np.nan, "xdrift"))
        t.add_column(Column(np.zeros((len(t),), dtype=bool), "astemplate"))

    return t