#!/usr/bin/env python3
#
'''
.. module:: HDF_showattributes
   :synopsis: Show attributes for given HDF 5 file 
.. moduleauthor:: Cor de Vries <c.p.de.vries@sron.nl>                  
                                                                                                                                                                                             
''' 
   
from tesfdmtools.hdf.HMUX import HMUX
from tesfdmtools.utils.widgets.filechooser import getfile
import sys,os
import argparse


#=====================================================================================

if __name__ == "__main__":

   parser = argparse.ArgumentParser(\
                     description="Show attributes for given HDF5 file")
   parser.add_argument('-ch','--channel',type=int,required=False,default=None,\
                     help='Channel number to use. Default is first available channel.')
   parser.add_argument('-o','--ofile',action='store_true',required=False,default=None,\
                     help='write output to output file. Do not show on screen')
   parser.add_argument('-f','--file',required=False,default=None,help='Directory or file of x-ray data HDF5 file(s)')

   args=parser.parse_args()

   if args.file is None:
      hfile=getfile(pattern='*.h5',path='.') 
   else:
      if os.path.isdir(args.file):
         hfile=getfile(pattern='*.h5',path=args.dir)
      else:
         hfile=args.file

   if hfile.strip(' \n') == '':
      sys.exit()

   if not os.path.isfile(hfile):
      sys.exit("Error, file does not exist: %s" % hfile)

   hdf=HMUX(filename=hfile)
   channel=args.channel
   if channel is None:
      channel=int(hdf.channels[0])
   conftable=hdf.channel[channel].freq_conf
   freqs=hdf.channel[channel].freqs
   pixel=freqs[0]

   txt=[os.path.basename(hfile)+':']
   for attrs in hdf.attrs.keys():
      txt.append("    %s = %s" % (attrs,hdf.attrs[attrs]))
#
   txt.append('')
   h1=10*"%11s" % tuple(conftable.dtype.names[0:10])
   h2=("%11s" % conftable.dtype.names[0]) + ((len(conftable.dtype.names)-10)*"%11s" % tuple(conftable.dtype.names[10:]))
   txt.append(h1)
   for i,pixel_index in enumerate(conftable['pixel_index']):
      ll='%10d ' % pixel_index
      for name in conftable.dtype.names[1:10]:
         element=conftable[name][i]
         if str(type(element)).find('int') >= 0:
            ll=ll+('%10d ' % element)
         else:
            ll=ll+('%11.5f' % element)
      txt.append(ll)
   txt.append('')
   txt.append(h2)
   for i,pixel_index in enumerate(conftable['pixel_index']):
      ll='%10d ' % pixel_index
      for name in conftable.dtype.names[10:]:
         element=conftable[name][i]
         if str(type(element)).find('int') >= 0:
            ll=ll+('%10d ' % element)
         else:
            ll=ll+('%11.5f' % element)
      txt.append(ll)
   txt.append('')     
#     
   txt.append("channel=%d:" % channel)
   for attrs in hdf.channel[channel].attrs.keys():
      txt.append("    %s = %s" % (attrs,hdf.channel[channel].attrs[attrs]))
   txt.append("channel[%d],pixel[%d],record=0:" % (channel,pixel))
   for attrs in hdf.channel[channel].freq[pixel].attrs.keys():
      txt.append("    %s = %s" % (attrs,hdf.channel[channel].freq[pixel].attrs[attrs]))

   if args.ofile:
      fff=os.path.basename(hfile).split('.')[0]
      ofnam='Attributes_'+fff+'.txt'
      ofile=open(ofnam,'w')
      for line in txt:
         ofile.write(line+'\n')
   else:

      for line in txt:
         print(line)

