;+
; Project     :	STEREO - SECCHI
;
; Name        :	XSECCHI_VSO_INGEST
;
; Purpose     :	Retrieve SECCHI data from the Virtual Solar Observatory
;
; Category    :	STEREO, SECCHI, Catalog
;
; Explanation : Widget version of the VSO Search function SECCHI_VSO_INGEST
;             : Searches for SECCHI data then copies to local machine.
;		    : If local acrhive is setup and recognized SCCINGEST 
;             : will run against that directory
;			 
; Syntax      :	XSECCHI_VSO_INGEST
;
;
; Outputs     :The relevant files are copied over.
;
; Calls       :	PARSE_STEREO_NAME, ANYTIM2UTC, UTC2TAI, SCC_DATA_PATH,
;               BREAK_FILE, MK_TEMP_DIR, DELVARX, TAI2UTC, VSO_SEARCH, UNIQ,
;               VSO_GET, SCCINGEST, QMSG, PROGRESSBAR
;
; History     : Kevin Wei, 14-Jan-2010
;               Version 2, 07-Oct-2010, William Thompson, correct QUIET keyword
;               Version 3, 30-Nov-2011, WTT, create archive directory if needed
;                       Delete temporary directory
;               Version 4, 18-Oct-2016, WTT, correct for changed CW_UT_RANGE
;                                            Call VSO_GET(/USE_NETWORK)
;                                            Rename variable LIST to LST
;-

pro xsecchi_vso_ingest_event, ev
 widget_control, ev.top, GET_UVALUE=state
 widget_control, ev.id, GET_UVALUE=uval
 uval = string(uval); Sidenote:IDL throws bizzare type mismatch error that returns 1

 ;;
 ; Get state of wigits and set proper params for VSO_SEARCH
 ;;

 widget_control, state[0] ,get_value=sat
 widget_control, state[1] ,get_value=tel
 widget_control, state[2] ,get_value=wave
 widget_control, state[3], get_value=date
 widget_control, state[4], get_value=out_dir

 if sat eq 0 then spacecraft = '' 
 if sat eq 1 then spacecraft = 'STEREO_A' 
 if sat eq 2 then spacecraft = 'STEREO_B'
 
 if tel eq 0 then telescope = ''
 if tel eq 1 then begin 
		widget_control, state[2], SENSITIVE=1
		telescope = 'EUVI'
	endif else begin
		widget_control, state[2], SENSITIVE=0
		widget_control, state[2], set_value=0
	endelse
 if tel eq 2 then telescope = 'COR1' 
 if tel eq 3 then telescope = 'COR2' 
 if tel eq 4 then telescope = 'HI1' 
 if tel eq 5 then telescope = 'HI2' 

 if wave eq 1 then wavelength = ''
 if wave eq 1 then wavelength = 171
 if wave eq 2 then wavelength = 195 
 if wave eq 3 then wavelength = 284 
 if wave eq 4 then wavelength = 304 

 
 CASE uval OF
  'SEARCH' : BEGIN
 ;;
 ; Create output directory
 ;;
			if '' ne STRCOMPRESS(out_dir, /REMOVE_ALL) then begin
				if not dir_exist(out_dir) then begin
        				mk_dir, out_dir
       				if not dir_exist(out_dir) then xmessage, $
             				'Unable to create directory ' + out_dir
    				endif
    				temp_dir = out_dir
    				do_sccingest = 0	
			end else begin
                            path = scc_data_path('a')
                            break_file, path, disk, dir
                            path = disk + dir
                            if not dir_exist(path) then begin
                                mk_dir, path
                                if not dir_exist(path) then xmessage, $
                                  'Unable to create directory ' + path
                            endif
                            mk_temp_dir, path, temp_dir, err=err
                            do_sccingest = 1
                            if err ne '' then begin
                                path = getenv('HOME')
                                mk_temp_dir, path, temp_dir
                                do_sccingest = 0
                            endif
			endelse
 ;;
 ; Search in 4 hour segments, Display and update progress bar while searching.
 ;;
			prog = obj_new("PROGRESSBAR",/fast_loop,text="Searching...")
                        tai1 = utc2tai(date[0])
                        tai2 = utc2tai(date[1])
			delvarx, lst
			t1 = tai1
			t2 = (t1 + 14400d0) < tai2
			inc = (14400d0 / (tai2-tai1) ) * 100
			bar = 0
			prog->start
			while t1 lt tai2 do begin
    				d1 = tai2utc(t1, /ccsds)
    				d2 = tai2utc(t2, /ccsds)
    				;xmessage, 'Searching between ' + d1 + ' and ' + d2
    				l = vso_search(d1, d2, provider='ssc', instrument='secchi', $
                    	source=spacecraft, detector=telescope, wave=wavelength, $
                    	quiet=quiet, _extra=_extra)
    				if datatype(l) eq 'STC' then begin
        				if n_elements(lst) eq 0 then lst = l else lst = [lst, l]
    				endif
    				t1 = t2
    				t2 = (t1 + 14400d0) < tai2
				bar = bar + inc
				prog->update,bar
				if prog->checkcancel() then break
			endwhile
			prog->update,100
			prog->destroy
			if n_elements(lst) eq 0 then begin
				xmessage, 'No files found' 
				file_delete, temp_dir
               endif else begin
 ;;
 ; Remove duplicates
 ;;
				s = sort(lst.fileid)
				lst = lst[s]
				u = uniq(lst.fileid)
				lst = lst[u]
 ;;
 ; Confirm that files should be copied
 ;;
				msg = ['Do you want to copy the '+ntrim(n_elements(lst)) + ' file(s) over?']
				answer = qmsg(lst.fileid,msg)
				if answer EQ 'yes' then begin
					prog = obj_new("PROGRESSBAR",/fast_loop,text="Downloading...",/nocancel)
					widget_control,/hourglass
					lstsize = size(lst)
					prog->start
					for index = 0, lstsize[1]-1 do begin
                                            status = vso_get(lst[index], out_dir=temp_dir, /force, $
                                                             quiet=quiet, /use_network, _extra=_extra)
                                            prog->update,double(index)/lstsize[1]*100
					endfor
					if do_sccingest then begin
                                            sccingest, temp_dir
                                            if not keyword_set(quiet) then $
                                              print, 'Deleting temporary directory ' + temp_dir
                                            file_delete, temp_dir
                                        endif
					prog->destroy
				endif else file_delete, temp_dir,/quiet
			endelse
		   END 

  'QUIT' : widget_control, ev.top, /destroy
   ELSE:
 ENDCASE
end

pro xsecchi_vso_ingest
 
 main = widget_base(title='VSO_Search', /column)
 mainB = widget_base(main,/row)

 date = cw_ut_range(mainB,value = [881193600.,881280000.],/nomsec,label = 'Search Range',/narrow)
 
 mainA = widget_base(main, /row)

 spacecraftvalues = ['Both','Ahead','Behind']
 spacecraftgroup = cw_bgroup(mainA,spacecraftvalues,/column,/exclusive, Label_top='Spacecraft',/frame)

 telescopevalues = ['All','EUVI','COR1','COR2','HI1','HI2']
 telescopegroup = cw_bgroup(mainA,telescopevalues,/column,/exclusive,Label_top='Telescope',/frame)
 
 euviwavelengthvalues = ['All','171','195','284','304']
 euviwavelengthgroup = cw_bgroup(mainA,euviwavelengthvalues,/column,/exclusive,Label_top='EUVI Wavelength',/frame)
 
 mainC = widget_base(mainA,/column)

 outlbl = widget_label(mainC,value='Output Directory')
 output = widget_text(mainC,uvalue='OUTPUT',/EDITABLE)

 btnSearch = widget_button(mainC,value ='Search',uvalue='SEARCH')
 btnQuit = widget_button(mainC, value ='Quit',uvalue='QUIT')

 ;;
 ; Set default value for buttons
 ;; 
 widget_control, telescopegroup, set_value = 0
 widget_control, spacecraftgroup, set_value = 0
 widget_control, euviwavelengthgroup, set_value = 0
 widget_control, euviwavelengthgroup, SENSITIVE=0

 state=[spacecraftgroup,telescopegroup,euviwavelengthgroup,date,output]
 widget_control, main, set_uvalue=state, /realize, /no_copy
 xmanager, 'xsecchi_vso_ingest' , /no_block, main
end


