######################################################################
### This is the function which are called in the 'contents' files
######################################################################
proc Content {file function header args} {
  global __content __path __type
  if {![file exists $__path/$file]} {
    puts "Warning: In $__type setup file \"$__path/contents\","
    puts "the file \"$file\" doesn't exists. Ignoring target."
    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

  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 == "contents"} continue
        if {![info exists __content($__type,$f)]} {
          set __content($__type,$f) [list "file: $f" "" "No description"]
        }
      }
    }
                                    
  }
}

######################################################################
### 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

  ### Update the save file from ver 1.1
  updateFromVer-1.1
  
  ### 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] "Initializing" "Initializing...Please wait"
  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

  
  ### 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 "Please select a predefined setup to load. If none of these are of your interest, press the \"Cancel\" button and none will be loaded. If You wish only to load some of the pages for a given setup, please select the \"Details\" button.\n\nNOTE: More information may be available for each setup. This help is reached by pressing the right mouse button on a setup"
  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 "Details" -command "loadDetails $init"
  button $w.buttons.cancel -text "Cancel" -command "loadEnd cancel $init"
  button $w.buttons.reset -text Reset -command "loadEnd reset $init"
  button $w.buttons.ok -text OK -command "loadEnd ok $init"
  button $w.buttons.help  -text Help -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
  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 "User Save Files"}
    {user-export "User Export Files"}
  }
  if {$from != "manage"} {
    lappend elms {system-file "System files"}
  }
  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 "NO Help" "No help were avilable for this setup" \
                info 0 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 \
        "\nIf you select this element, the Dotfile Generator will import the original dotfile (ie. the one you wanted to configure in the first place)\n"
  }
  $w configure -state disabled
  bindtags $w None
}
