######################################################################
### This is the function which are called in the 'contents' files
######################################################################
proc Content {file function header args} {
  global __content __path __type __language
  if {![file exists $__path/$file]} {
    puts [langExp %s $__path/contents [langExp %t $__type $__language(load,1)]]
    puts [langExp %s $file $__language(load,3)]
    return
  }
  set __content($__type,$file) [list $header $function [join $args]]
}

######################################################################
### This function read all the 'contents' files, and the function
### associated with them.
######################################################################
proc readContent {} {
  global __type argv module __path __content __language

  foreach elm "{user-export   [myGlob ~]/.dotfile/$module(name)/export-files}\
               {user-save     [myGlob ~]/.dotfile/$module(name)/save-files}  \
               {system-file [lindex $argv 1]/exports}" {
    set __type [lindex $elm 0]
    set dir [lindex $elm 1]
    if {[file exists $dir/functions]} {
      source $dir/functions
    }
    if {[file exists $dir/contents]} {
      set __path $dir
      source $dir/contents
    }
    if {![catch "myGlob $dir/*"]} {
      foreach file [myGlob $dir/*] {
        regexp "^[myGlob $dir]/(.*)\$" $file all f
        if {$f == "CVS"} continue
        if {$f == "RCS"} continue
        if {$f == "contents"} continue
        if {![info exists __content($__type,$f)]} {
          set __content($__type,$f) [list "file: $f" "" $__language(load,5)]
        }
      }
    }
                                    
  }
}

######################################################################
### This function returns true if there exists any load- or save files
######################################################################
proc existsLoadFiles {} {
  global __content module
  if {[array names __content] != "" || [info exists module(parser)]} {
    return 1
  } else {
    return 0
  }
}

######################################################################
### This function initialize the module, and load call the load
### function, which offers a load page
######################################################################
proc initialize_and_load {} {
  global __progList __editInfo __initFunc changeElm __language

  ### initialize all the pages to a default value
  foreach page $__progList {
    setBasic $page
  }

  ### read the setup files
  readContent

  if {[existsLoadFiles]} {
    ### load a setup
    set __editInfo(name) ""
    loadPage 1
  } else {
    foreach page $__progList {
      set changeElm "init"
      set __editInfo(name) $page
      linkVars $page __$page top
      uplevel \#0 $__initFunc($page)
      unlink $page top ""
      set __editInfo(name) ""
    }
  }

  ### initialize the rest of each page
  timeWindow [llength $__progList] $__language(load,6) $__language(load,7)
  foreach page $__progList {
    setDefaultsOnPage $page
    incrTimeWindow
  }
  destroyTimeWindow
}

######################################################################
### This function creates the load file
######################################################################
proc loadPage {init} {
  global __content __loadOverWrite __loadMerge __progList __editInfo
  global __fileToLoad __loadSetup __var2Path __language

  
  ### First delete any visual page
  set menu $__editInfo(name)
  if {$__editInfo(name) != ""} {
    unlink $__editInfo(name) top ""
    set __editInfo(name) ""
  }
  catch "destroy .edit"
  catch "unset __var2Path"

  set w [toplevel .load]
  if {![info exist __loadSetup]} {
    set __loadSetup 1
  }
  wm resizable $w 0 1

  pack [frame $w.frame] -expand 1 -fill both
  set frame $w.frame

  ### just a dummy label to get default font.
  label $w.dummy

  text $frame.text -yscrollcommand "$frame.scroll set" -wrap word  \
      -cursor left_ptr -font [$w.dummy cget -font]
  scrollbar $frame.scroll -command "$frame.text yview"
  pack $frame.text -side left -fill both -expand 1
  pack $frame.scroll -side left -fill y -expand 0

  insertIntoTextBox $frame.text create
  
  ### Setting up the help text
  label $w.help -wraplength 500 -justify left -text $__language(load,8)
  pack $w.help -fill x -expand 0
  
  ### packing details and the cancel button
  pack [frame $w.buttons] -fill x -expand 0
  button $w.buttons.details -text $__language(load,9) -command "loadDetails $init"
  button $w.buttons.cancel -text $__language(load,10) -command "loadEnd cancel $init"
  button $w.buttons.reset -text $__language(load,11) -command "loadEnd reset $init"
  button $w.buttons.ok -text $__language(ok) -command "loadEnd ok $init"
  button $w.buttons.help  -text $__language(load,12) -command "help`gotoTag loadpage"
  pack $w.buttons.details $w.buttons.reset  $w.buttons.cancel $w.buttons.ok $w.buttons.help -side right -fill x
  if {$init} {
    $w.buttons.reset configure -state disabled
  }
  if {![info exist __fileToLoad]} {
    $w.buttons.ok configure -state disabled
    $w.buttons.details configure -state disabled
  }

  ### Set which pages to load
  set __loadOverWrite $__progList
  set __loadMerge {}
  
  ### Now wait until the page is destoyed, which will indicate
  ### that the user is finished.
  tkwait window $w
  if {$menu != ""} {
    loadMenu $menu
  }
}

######################################################################
### This function setup a call to the details page
######################################################################
proc loadDetails {init} {
  global __fileToLoad __loadOverWrite __loadMerge
  if {[lindex $__fileToLoad 0] == "user-save" || $init} {
    set merge 0
  } else {
    set merge 1
  }
  if {[lindex $__fileToLoad 0] == "user-save"} {
    set loadFile 1
  } else {
    set loadFile 0
  }
  set res [createDetails $merge $loadFile]
  set __loadOverWrite [lindex $res 0]
  set __loadMerge [lindex $res 1]
}

######################################################################
### This function is selected, when the user press either
### the OK, Cancel or Reset button
######################################################################
proc loadEnd {method init} {
  global module argv __loadOverWrite __fileToLoad __editInfo __loadMerge
  global __loadPage __progList __clean changeElm __initFunc __system

  if {[info exists __fileToLoad]} {
    set type [lindex $__fileToLoad 0]
    set fileName [lindex $__fileToLoad 1]
  }
  ### unset clean bit
  if {$method == "reset" || ($method == "ok" && $type != "user-save")} {
    foreach page [concat $__loadOverWrite $__loadMerge] {
      foreach elements [array names __clean __$page*] {
        eval unset __clean($elements)
      }
    }
  }

  ### call init for all pages, which is not loaded
  if {$init} {
    if {$method == "ok" || $method == "reset"} {
      set list [concat $__loadOverWrite $__loadMerge]
    } else {
      set list ""
    }
    foreach page $__progList {
      if {[lsearch $list $page ] == -1} {
        set changeElm "init"
        set __editInfo(name) $page
        linkVars $page __$page top
        uplevel \#0 $__initFunc($page)
        unlink $page top ""
        set __editInfo(name) ""
      }
    }
  }

  ### OK, means load pages
  if {$method == "ok"} {
    wm withdraw .load
    foreach page $__loadOverWrite {
      unsetPage $page
      setBasic $page
      if {$type != "user-save"} {
        set changeElm "init"
        set __editInfo(name) $page
        linkVars $page __$page top
        uplevel \#0 $__initFunc($page)
        unlink $page top ""
        set __editInfo(name) ""
      }
    }

    if {$fileName == "--DOTFILE--"} {
      if {![file exists ~/.dotfile]} {
        eval "exec $__system(mkdir) [myGlob ~/].dotfile"
      }
      $module(parser) "~/.dotfile/tmp.export" \
          [concat $__loadOverWrite $__loadMerge]
    }
    switch $type {
      user-export {
        if {$fileName == "--DOTFILE--"} {
          import-file [myGlob ~]/.dotfile/tmp.export
        } else {
          import-file [myGlob ~]/.dotfile/$module(name)/export-files/$fileName
        }
      }
      user-save {
        loadSaveFile [myGlob ~]/.dotfile/$module(name)/save-files/$fileName
        if {$__editInfo(loadFile) != "" && $__editInfo(loadFile) != $fileName} {
          set __editInfo(loadFile) ""
        } else {
          set __editInfo(loadFile) $fileName
        }
      }
      system-file {
        ### what a dirty hack :-(
        regsub {(.export)$} $fileName .save filenm

        if {[llength $__loadMerge] == 0 &&
            [file exists [lindex $argv 1]/save-files/$filenm]} {
          loadSaveFile [lindex $argv 1]/save-files/$filenm
        } else {
          import-file  [lindex $argv 1]/exports/$fileName
        }
      }
    }
  }

  ### Reset, means reset pages
  if {$method == "reset"} {
    foreach page [concat $__loadOverWrite $__loadMerge] {
      unsetPage $page
      setBasic $page
      set changeElm "init"
      set __editInfo(name) $page
      uplevel \#0 $__initFunc($page)
      ### initialize the rest of each page
      setDefaultsOnPage $page
    }
  }

  ### delete the export temporery file
  if {$method == "ok" && $fileName == "--DOTFILE--"} {
    exec rm [myGlob ~]/.dotfile/tmp.export
  }
  destroy .load
}

proc loadSaveFile file {
  global __progList __loadPage __loadOverWrite __editInfo __loadMerge
  ### First build an associative array, which is mutch faster
  ### than serching in a list
  foreach page $__progList {
    set __loadPage($page) 0
  }
  foreach page $__loadOverWrite {
    set __loadPage($page) 1
  }
  foreach page $__loadMerge {
    set __loadPage($page) 1
  }
  uplevel \#0 source $file
  unset __loadPage
}

######################################################################
### This function inserts text into the textbox in the load page
### and in the manage save/export files page.
######################################################################
proc insertIntoTextBox {w from} {
  global __content __fileToLoad module __language
  set first 1
  set firstFile 1

  ### just a dummy label to get default font.
  label $w.dummy

  ### line tag, which makes horizontol lines, which does not wrap!
  $w tag configure line -wrap none
  $w tag configure center -justify center
  $w tag configure indent -lmargin1 25 -lmargin2 25


  ### run through each category
  set line 0
  set elms "{user-save $__language(load,17)} {user-export $__language(load,16)}"
  if {$from != "manage"} {
    lappend elms "system-file $__language(load,18)"
  }
  foreach elm $elms {

    set type [lindex $elm 0]
    set text [lindex $elm 1]
    if {[array names __content $type*] != ""} {
      ### insert the header
      if {!$first} {
        set i [$w index insert]
        $w insert end "____________________________________________________________________________________________________________________________________________________"
        $w tag add line $i insert
        $w insert end \n\n
      } else {
        set first 0
      }
      set i [$w index insert]
      $w insert end $text\n
      $w tag add center $i insert

      ### insert each of the save/export files
      foreach pair [array names __content $type*] {
        regexp "^$type,(.*)\$" $pair all fileName
        set header [lindex $__content($pair) 0]
        set command [lindex $__content($pair) 1]
        set text [lindex $__content($pair) 2]
        set index [$w index insert]

        ### creating the header
        if {$from == "manage"} {
          radiobutton $w.$line -text "$header ($fileName)" \
              -variable __fileToLoad \
              -value "$type $fileName" -justify left
        } else {
          radiobutton $w.$line -text $header -variable __fileToLoad \
              -value "$type $fileName" -justify left
        }
        if {$firstFile} {
          set __fileToLoad "$type $fileName"
          set firstFile 0
        }
        $w window create insert -window $w.$line
        $w insert end \n

        ### creating the description
        if {$text != ""} {
          set index2 [$w index insert]
          $w insert end $text\n
          $w tag add ${type}_$fileName $index insert
          $w tag configure ${type}_$fileName  -font [$w.dummy cget -font]
          $w tag add indent $index2 insert
        }

        ### binding help
        if {$command == ""} {
          set command {
            tk_dialog .nohelp $__language(load,13) $__language(load,14) \
                info 0 $__language(ok)
          }
        }
        $w tag bind ${type}_$fileName <3> $command
        bind $w.$line <3> $command
        incr line
      }
    }
  }
  if {[info exists module(parser)] && $from != "manage"} {
    if {!$first} {
      set i [$w index insert]
      $w insert end "____________________________________________________________________________________________________________________________________________________\n"
      $w tag add line $i insert
    }
    radiobutton $w.dotfile -text "Import from the dotfile" \
              -variable __fileToLoad \
        -value [list user-export  "--DOTFILE--"] -justify left
    $w window create insert -window $w.dotfile
    $w insert insert \
        $__language(load,15)
  }
  $w configure -state disabled
  bindtags $w None
}
