#
# <20230704.1842.58>
#
# This file contains a 'twapi' centric directory fetch & process routine.
#
# This code modifies variables in the callers space:
#
#  sortlist is set to a list of "'sort key' 'name'"
#  dl       is set to the full directory list
#
#  The user variable 'inst' in the callers space is used to get/set the following:
#
#  ::glob($inst,lastmtime)   set the the given 'dir's current mtime
#  ::config(fileshow,all)    if true hidden files are included in 'dl'
#  ::config(fileshow,sort)   is used to build the sort keys
#  ::config(fileshow,dirs)   is used the build the sort key (where directories are to be)
#
proc getMSWdirList {dir} {
  global config glob
  upvar sortlist sortlist inst inst dl dl

  set glob($inst,lastmtime) [file mtime $dir]
  set dl {}
  set dirTok [twapi::find_file_open $dir/* -detail full]
  while {[twapi::find_file_next $dirTok dirInfo]} {
    array set dirData $dirInfo
    set linkName {}
    set attrsList [twapi::decode_file_attributes $dirData(attrs)]
    if {!$config(fileshow,all) && "hidden" in $attrsList} {continue}
    # Debug code....
    # if {$dirData(name) == "OneDrive"} {
    #   frputs attrsList' dirInfo
    # }
    # End of Debug code...
    set type ""
    if {"reparse_point" in $attrsList} {
      if {[catch {file link $dirData(name)} linkName] != 0} {
	set linkName {}
      } else {
	set type "l" 
      }
    }
    if {"directory" in $attrsList} {
      set type "${type}d"
    } elseif {$type == ""} {
      set type "n"
    }
    if {[file extension $dir/$dirData(name)] == ".lnk"} {
      if {[catch {LnkFile $dir/$dirData(name)} linkName] == 0} {
	set type [expr {[file isdir $linkName ] ? {wld} : {wl}}]
      } else {
	set linkName " "
      }
    }
    
    foreach time {ctime atime mtime} {
      set $time [twapi::large_system_time_to_secs_since_1970 $dirData($time)]
    }
    set tmp [switch -exact $config(fileshow,sort) {
      atime     {format "%011d" $atime }
      ctime     {format "%011d" $ctime }
      mtime     {format "%011d" $mtime }
      ratime    {format "%011d" [expr 2147483647 - $atime]}
      rctime    {format "%011d" [expr 2147483647 - $ctime]}
      rmtime    {format "%011d" [expr 2147483647 - $mtime]}
      size      {format "%011d" $statinfo(size) }
      extension {file extension $dirData(name)}
      default   {expr { " "}}
    }]
    set sortval_d [lsearch {dirsfirst mixed dirslast} $config(fileshow,dirs)]
    switch -exact $type {
      wl -
      n  -
      l  {set sortval 1$tmp}
      d   -
      wld -
      ld  {set sortval $sortval_d$tmp}
    }

    # entries in this list:
    # sortval fname type size mtime mode userid linkname links atime ctime
    lappend dl [list $sortval $dirData(name) $type $dirData(size) $mtime \
			{} {} $linkName {1}  $atime $ctime]
    # the sortlist entries:
    # sortval [list name]
    lappend sortlist [list $sortval $dirData(name)]
  }
  twapi::find_file_close $dirTok
}
