; $Id: hfbsfilelist.pro,v 1.3 2007/04/04 20:42:57 kneller Exp $
;###############################################################################
;
;FILENAME:
;        hfbsfilelist.pro
;
;PURPOSE:
;
;CATEGORY:
;       File chooser utility.
;
;METHODS:
;    hfbsFileList_event
;    hfbsFileList_getQandComment
;    hfbsFileList_get_value
;    hfbsFileList_cleanup
;    launch_hfbsFileList
;    hfbsFileList
;
;SYNTAX: fn = hfbsfilelist(startdir='\\Charlotte\ICP Data\hfbs\200702',title='Select .hfbs data files:')
;
;
; AUTHOR:
; Larry Kneller
; NIST Center for Neutron Research
; 100 Bureau Drive, Gaithersburg, MD 20899
; United States
; kneller@nist.gov  301-975-8839
; Apr 02 2007
;
; LICENSE:
; The software in this file is written by an employee of
; National Institute of Standards and Technology
; as part of the DAVE software project.
;
; The DAVE software package is not subject to copyright protection
; and is in the public domain. It should be considered as an
; experimental neutron scattering data reduction, visualization, and
; analysis system. As such, the authors assume no responsibility
; whatsoever for its use, and make no guarantees, expressed or
; implied, about its quality, reliability, or any other
; characteristic. The use of certain trade names or commercial
; products does not imply any endorsement of a particular product,
; nor does it imply that the named product is necessarily the best
; product for the stated purpose. We would appreciate acknowledgment
; if the DAVE software is used or if the code in this file is
; included in another product.
;
;###############################################################################


pro hfbsfilelist_help_event,event

    uname = widget_info(event.id,/uname)
    tlb = event.handler
    stash = widget_info(tlb,find_by_uname='HFBSFILELISTHELPCLOSE')
    widget_control,stash,get_uvalue=pstate

    case uname of
    'HFBSFILELISTHELPCLOSE':begin
        widget_control,tlb,/destroy
    end
    else:
    endcase


end;hfbsfilelist_help_event


function HFBSFileList_helpstring

    s = [ $
         'This program displays the list of .hfbs files ', $
         'in the selected directory. ', $
         'Select files from the list to open and then ', $
         'choose "Open Selected File(s)" from the file menu.',$
         'This will return the list of files to the calling program.',$
         'To browse another directory select "Choose New Directory" ',$
         'from the file menu.' $
        ]
    return,s
end;HFBSFilelist_helpstring












;###############################################################################
;
;NAME:
;        HFBSFileList_event
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro HFBSFileList_event,event


    uname = widget_info(event.id,/uname)



    tlb = event.handler

;    print,'tlb=',tlb
    stash = widget_info(tlb,find_by_uname='HFBSFILELISTSTASH')

;    print,'stash=',stash
    widget_control,stash,get_uvalue=pstate

    case uname of
    'HFBSFILELISTTLB':begin
        ;print,event.x,event.y

        if !version.os eq 'Win32' then begin
            xresizemagic = 15
            yresizemagic = 55
        endif else begin
            xresizemagic = 10
            yresizemagic = 40
        endelse



        tlbgeom = widget_info(tlb,/geometry)
        list = widget_info(tlb,find_by_uname='HFBSFILELISTLIST')
        text = widget_info(tlb,find_by_uname='HFBSFILELISTTEXT')

        textgeom = widget_info(text,/geometry)

        widget_control,list,scr_xsize=tlbgeom.scr_xsize-xresizemagic,$
                            scr_ysize=tlbgeom.scr_ysize-textgeom.scr_ysize-yresizemagic
        widget_control,text,scr_xsize=tlbgeom.scr_xsize-xresizemagic


    end;HFBSFILELISTTLB
    'HFBSFILELISTOPEN':begin
        dir = dialog_pickfile(/directory,path = (*pstate).startdir)

        if dir ne '' then begin
            (*pstate).startdir = dir
            filter = (*pstate).filter

            fullfiles = file_search(dir+filter)
            widget_control,(*pstate).showcomments,get_value=showcomment
            ;print,'Showcomment=',showcomment


            HFBSFileList_getQandComment,fullfiles,list=list,showcomment=showcomment[0]

            id = widget_info(tlb,find_by_uname='HFBSFILELISTLIST')
            tx = widget_info(tlb,find_by_uname='HFBSFILELISTTEXT')

            widget_control,tx,set_value=dir
            widget_control,id,set_value=list,set_uvalue=fullfiles
        endif

    end;HFBSFILELISTOPEN
    'HFBSFILELISTUPDATE':begin

        dir = (*pstate).startdir

        ;print,dir
        if dir ne '' then begin
            (*pstate).startdir = dir
            filter = (*pstate).filter

            fullfiles = file_search(dir+path_sep()+filter)
            widget_control,(*pstate).showcomments,get_value=showcomment

            HFBSFileList_getQandComment,fullfiles,list=list,showcomment=showcomment[0]

            id = widget_info(tlb,find_by_uname='HFBSFILELISTLIST')
            tx = widget_info(tlb,find_by_uname='HFBSFILELISTTEXT')

            widget_control,tx,set_value=dir
            widget_control,id,set_value=list,set_uvalue=fullfiles
        endif

    end;HFBSFILELISTUPDATE
    'HFBSFILELISTQUIT':begin
        widget_control,tlb,/destroy
    end;HFBSFILELISTQUIT
    'HFBSFILELISTSTASH':begin

    end;HFBSFILELISTLIST
    'HFBSFILELISTHELP':begin

        (*pstate).helpbase = widget_base(title='About HFBS File List:',/floating,/modal,$
                                            group_leader = tlb,/col)

        text = HFBSFileList_helpstring()
        xsize = max(strlen(text))
        ysize = n_elements(text)
        t1 = widget_text((*pstate).helpbase,ysize=ysize,xsize=xsize,value=text)
        (*pstate).helpclose = widget_button((*pstate).helpbase,value='Close',uname='HFBSFILELISTHELPCLOSE',uvalue=pstate)
        widget_control,(*pstate).helpbase,/realize
        xmanager,'HFBSFILELIST_HELP',(*pstate).helpbase,/no_block


    end;HFBSFILELISTHELP

    'HFBSFILELISTOPENSELECTION':begin
        list = widget_info(event.handler,find_by_uname='HFBSFILELISTLIST')

        widget_control,list,get_uvalue = fulllist

        selection = widget_info(list,/list_select)

        count = n_elements(selection)
        if count gt 0 then begin
                if selection[0] ne -1 then begin
                    if ptr_valid((*pstate).selectedfiles) then ptr_free,(*pstate).selectedfiles
                    (*pstate).selectedfiles = ptr_new(fulllist[selection])
                    widget_control,tlb,/destroy
                endif else begin
                    void = dialog_message('No files selected.',/info)
                endelse
        endif;count

    end;HFBSFILELISTOPENSELECTION
    else:
    endcase

end;HFBSFileList_event



;###############################################################################
;
;NAME:
;        HFBSFileList_getQandComment
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro HFBSFileList_getQandComment,full_list,list=list,showcomments=showcomments

    if n_elements(showcomments) eq 0 then showcomments = 0

    if full_list[0] eq '' and n_elements(full_list) eq 1 then begin
        nfiles = 0
    endif else begin
        nfiles = n_elements(full_list)
    endelse

    prog = nseprogress([nfiles],title='Searching files . . .',labels=['File#: '],xsize=200)

;    base = widget_base(title='Searching files . . .',xoffset=300,yoffset = 300)
;    prog = cw_progress(base,value=[nfiles])
;    widget_control,base,/realize

;    print,nfiles
;    help,full_list
;    print,transpose(full_list)

    if nfiles gt 0 then begin
        q = strarr(nfiles)
        ;comment = strarr(nfiles)
        list = string(lindgen(nfiles),format='(i6)')

        line = ''

        CATCH, Error_status
        ;HANDLE ERRORS IN READING THE DATA FILE.
        IF (Error_status NE 0) THEN BEGIN

            ;widget_control,(*pstate).showcomments,get_value=showcomment
            ;print,'showcomment=',showcomment
            ;free_lun,lun,/force
            print,'HFBSFileList_getQandComment DATA FILE '+file_basename(full_list[i])+' IS INCOMPLETE.'

            ;help,/traceback
            CATCH, /CANCEL
        ;return
        ENDIF



        for i=0,nfiles-1 do begin

            nseprogress_step,prog


;IF YOU WANT TO VIEW COMMENTS AS WELL.
            ;widget_control,prog,set_value=[i]
            if full_list[i] ne '' then begin

                list[i] = string(i,format = '(i6)') + '   ' + file_basename(full_list[i])


                if showcomments eq 0 then begin

                    comment = ''
                    list[i] = list[i] + '   ' + comment

                endif else begin

                    nlines = file_lines(full_list[i])
                    if nlines gt 0 then begin


                        ;COMMENT ON FIRST LINE OF AN HFBS FILE.
                        openr,lun,full_list[i],/get_lun
                        readf,lun,line
                        free_lun,lun


                        segs = strsplit(line,':',/regex,/extract)

                        comment = ''
                        if n_elements(segs) ge 2 then begin
                            for iii = 1, n_elements(segs)-1 do begin
                                comment = comment + segs[iii]
                            endfor;iii
                        endif
                        list[i] = list[i] + '   ' + comment
                    endif;nlines

                endelse
            endif;NULL FILENAME
        endfor;i
    endif else begin    ;nfiles gt 0

        list = ['']

    endelse
    nseprogress_close,prog

end;HFBSFileList_getQandComment


;###############################################################################
;
;NAME:
;        HFBSFileList_get_value
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function HFBSFileList_get_value,id
    widget_control,id,get_uvalue=value
    return,value
end;HFBSFileList_get_value

;###############################################################################
;
;NAME:
;        HFBSFileList_cleanup
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro HFBSFileList_cleanup,id
    ;print,'HFBSFileList_cleanup'
;    widget_control,id,get_uvalue = pstate
;    if ptr_valid(pstate) then ptr_free,pstate
end;HFBSFileList_cleanup


;###############################################################################
;
;NAME:
;        HFBSFileList
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
function HFBSFileList,group_leader=group_leader,      $
                      startdir=startdir,              $
                      notify_ids = notify_ids,        $
                      data_dir = data_dir,            $
                      work_dir = work_dir,            $
                      dave_id = dave_id,$
                      filter=filter,$
                      title=title,$
                      write=write,$
                      read=read,$
                      commentcheck=commentcheck,$
                      multiple_select=multiple_select


    if n_elements(multiple_select) eq 0 then multiple_select = 1
    if n_elements(write) eq 0 then write = 0
    if n_elements(read) eq 0 then read = 0
    if n_elements(title) eq 0 then title = 'HFBS File List'
    if n_elements(commentcheck) eq 0 then commentcheck = 0

    tlb = widget_base(title=title,$
                        group_leader=group_leader,$
                        /col,$
                        xoffset = 300, yoffset = 300,$
                        mbar = bar,$
                        /tlb_size_events,$
                        uname='HFBSFILELISTTLB')

    stash = widget_button(bar,/menu,value='File',UNAME='HFBSFILELISTSTASH',kill_notify='HFBSFileList_cleanup')
;    open =      widget_button(stash,value='Choose New Directory',UNAME='HFBSFILELISTOPEN')
;    openfiles = widget_button(stash,value='Open Selected File(s)',uname='HFBSFILELISTOPENSELECTION')
    Quit =      widget_button(stash,value='Quit',uname='HFBSFILELISTQUIT')

    helpmenu = widget_button(bar,value='Help',/menu)
    help = widget_button(helpmenu,value='Help on HFBSFileList',uname='HFBSFILELISTHELP')



    if n_elements(startdir)     eq 0 then startdir = ''
    if n_elements(data_dir)      eq 0 then data_dir = ''
    if n_elements(work_dir)      eq 0 then work_dir = ''
    if n_elements(dave_id)      eq 0 then dave_id = 0L
    if n_elements(notify_ids)   eq 0 then notify_ids = 0L
    if n_elements(group_leader) eq 0 then group_leader = 0L
    if n_elements(filter) eq 0 then filter = '*.hfbs'

    if n_elements(startdir) eq 0 then startdir = '.'

    dirlabel = 0L;widget_button(bar,value=startdir,xsize)

    fullfiles = file_search(startdir+path_sep()+filter)

    HFBSFileList_getQandComment,fullfiles,list=files,showcomments = 0

    openlabel = 'Open Selected File(s)'
    multiple = multiple_select
    if write ne 0 then begin
        openlabel = 'Choose output file'
        multiple = 0
    endif


    list = widget_list(tlb,xsize=100,ysize = 15,$
                        value=files,uname='HFBSFILELISTLIST',$
                        multiple = multiple,$
                        func_get_value='HFBSFileList_get_value',$
;                        pro_set_value ='HFBSFileList_set_value',$
                        uvalue=fullfiles $
                        )

    open =      widget_button(tlb,value='Choose New Directory',UNAME='HFBSFILELISTOPEN')
    openfiles = widget_button(tlb,value=openlabel,uname='HFBSFILELISTOPENSELECTION')
    cancel =    widget_button(tlb,value='Cancel',uname='HFBSFILELISTQUIT')

    if commentcheck ne 0 then begin
        commentsrow = widget_base(tlb,/row)
    endif else begin
        commentsrow = widget_base(/row)
    endelse
    showcomments = cw_bgroup(commentsrow,'Show File Comments (THIS IS SLOW!)',/nonexclusive,/row)
    update = widget_button(commentsrow,value='Update List',UNAME='HFBSFILELISTUPDATE')

    text = widget_text(tlb, xsize=100,$
                            value=startdir,$
                            uname='HFBSFILELISTTEXT')

    state = {tlb:tlb,open:open,openfiles:openfiles,quit:quit,$
            group_leader:group_leader,      $
            startdir:startdir,              $
            notify_ids : notify_ids,        $
            data_dir : data_dir,            $
            work_dir : work_dir,            $
            dave_id : dave_id,$
            showcomments:showcomments,$
            update:update,$
            text : text,$
            helpbase:0L,$
            helpclose:0L,$
            filter:filter,$
            selectedfiles:ptr_new(strarr(1))}

    pstate = ptr_new(state)

    widget_control,stash,set_uvalue=pstate
    widget_control,tlb,/realize
    HFBSFileList_event,{handler:tlb,id:update}

    xmanager,'HFBSfileList',tlb;,/no_block

    if (*((*pstate).selectedfiles))[0] ne '' then begin

        selectedfiles = (*((*pstate).selectedfiles))

        if ptr_valid((*pstate).selectedfiles) gt 0 then ptr_free,(*pstate).selectedfiles
        if ptr_valid(pstate) then ptr_free,pstate

        return,selectedfiles
    endif else begin
        return,''
    endelse

end;HFBSFileList

