#!/usr/bin/python
"""
Created on Tue Sep 23 16:07:19 2014
@author: mints
"""

from astropy.io import fits as pyfits
import texttable
import argparse
import sys
from fnmatch import fnmatch

parser = argparse.ArgumentParser(description=""".""",
                    formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-f', '--filename', type=str, default=None,
                    help='File to use')

parser.add_argument('-k', '--keys', type=str, default=None,
                    help='Header keys to use (mask can be given)')

parser.add_argument('-t', '--table', type=int, default=None,
                    help='Table index')

parser.add_argument('--history', action="store_true",
                    default=False,
                    help='Show history')

parser.add_argument('--comments', action="store_true",
                    default=False,
                    help='Show comments')

parser.add_argument('--data', action="store_true",
                    default=False,
                    help='Show data')

parser.add_argument('-o', '--onlydata', action="store_true",
                    default=False,
                    help='Show data only (no header information')

args = parser.parse_args()

fits = pyfits.open(args.filename)


def single_table_all():
    header = fits[args.table].header
    print 'Table name: ', fits[args.table].name
    table = texttable.Texttable()
    table.set_cols_align(['l', 'l', 'l'])
    width = [0, 0, 0]
    history = ''
    comment = ''
    table.set_deco(texttable.Texttable.HEADER)
    table.add_rows([['Key', 'Value', 'Comment']])
    for item in header.cards:
        if item.keyword == 'HISTORY':
            if item.value.startswith('Created') or \
               item.value.startswith('Modified') or \
               item.value.startswith('bad pixel') :
                history = '%s\n%s' % (history, item.value)
            elif item.value.startswith('Mode'):
                history = '%s\n    %s' % (history, item.value)
            else:
                history = '%s%s' % (history, item.value)
        elif item.keyword == 'COMMENT':
            comment = '%s\n%s' % (comment, item.value)
        elif item.keyword == 'TFIELDS' or item.keyword.startswith('TTYPE') or \
            item.keyword.startswith('TFORM') or item.keyword.startswith('TUNIT'):
            continue
        else:
            row = [item.keyword, item.value, item.comment]
            table.add_row(row)
            for i in xrange(3):
                if len(str(row[i])) > width[i]:
                    width[i] = len(str(row[i]))
    for i in xrange(3):
        if width[i] > 50:
            width[i] = 50
    table.set_cols_width(width)
    if not args.onlydata:
        print table.draw()
    if hasattr(fits[args.table], 'columns'):
        table = texttable.Texttable()
        table.set_cols_align(['l', 'c', 'l'])
        width = [0, 6, 0]
        table.set_deco(texttable.Texttable.HEADER)
        table.add_rows([['Name', 'Type', 'Unit']])
        for column in fits[args.table].columns:
            row = [column.name, column.format, column.unit]
            table.add_row(row)
            for i in xrange(3):
                if len(str(row[i])) > width[i]:
                    width[i] = len(str(row[i]))
        table.set_cols_width(width)
    if not args.onlydata:
        if hasattr(fits[args.table], 'columns'):
            print 'Columns:'
            print table.draw()
        if args.history:
            print history
        if args.comments:
            print comment
    if args.data and hasattr(fits[args.table], 'columns'):
        for column in fits[args.table].columns:
            print column.name, ' ',
        print

        for row in fits[args.table].data:
            for item in row:
                print item, ' ',
            print

def multiple_tables(keys, ftables):
    table = texttable.Texttable()
    table.set_cols_align(['l', 'l', 'l', 'l'])
    width = [len(t) for t in ['Table', 'Key', 'Value', 'Comment']]
    table.set_deco(texttable.Texttable.HEADER)
    table.add_rows([['Table', 'Key', 'Value', 'Comment']])
    for ftable in ftables:
        header = ftable.header
        for item in header.cards:
            for mask in keys:
                if fnmatch(item.keyword, mask):
                    row = [ftable.name, item.keyword, item.value, item.comment]
                    table.add_row(row)
                    for i in xrange(4):
                        if len(str(row[i])) > width[i]:
                            width[i] = len(str(row[i]))
    table.set_cols_width(width)
    print table.draw()

if args.table is None:
    if args.keys is None:
        print fits.info()
        sys.exit()
    else:
        multiple_tables(args.keys.split(','), fits)
elif args.keys is None:
    single_table_all()
else:
    multiple_tables(args.keys.split(','), [fits[args.table]])
