######################################################
#                TkTeXeditor
#        Distributed under GNU Public License
# Author: Sergey Kalinin (BanZaj) banzaj@lrn.ru
# Copyright (c) "CONERO lrn", 2000, http//conero.lrn.ru
######################################################
set types {
    {"TeX files" {.tex}}
    {"Html files" {.html}}
    {"Text files" {.txt}}
    {"All files" *}
}
set typeImage {
    {"GIF files" {.gif}}
    {"PNG files" {.png}}
    {"JPEG files" {.jpeg}}
    {"All files" *}
}

proc FileDialog {operation} {
    global dir font tree nb files treeStruct in lastNode \
    activeFile color status lblList ver sysenc release types
    ## settings variable for tree section ##
    set in(c) 0 ;# chapter counter
    set in(p) 0 ;# part counter
    set in(s) 0 ;# section counter
    set in(ss) 0 ;# subsection counter
    set in(sss) 0 ;# subsubsection counter
    set in(par) 0 ;# paragraph cponter
    set in(spar) 0 ;# subparagraph cponter
    set lastNode "root"
    
    
    if {$operation == "new"} {
        NewFileDialog
    } elseif {$operation == "new_templ"} {
        TemplateDialog
    } elseif {$operation == "open"} {
        set file [tk_getOpenFile -initialdir $dir(current) -filetypes $types -parent .]
        #puts "$file"
        if {$file == ""} {return}
        # call EditFile procedure
        EditFile $file
    } elseif {$operation == "save"} {
        if [info exists activeFile] {
            set node $activeFile
        } else {
            #set node [$nb raise]
            return
        }
        if {$node == "newproj" || $node == "" || $node == "debug"} {
            return
        }
        if {[info exists files($node)] == 0} {
            return
        }
        
        set text "$nb.f$node.f.text"
        set fullPath [lindex $files($node) 0]
        set encode [lindex $files($node) 2] ;# document encoding
        set folder [file dirname $fullPath]
        set file [file tail $fullPath]
        #set contents [encoding convertfrom $sysenc [$text get 0.0 end]]
        #set contents [encoding convertto $encode [$text get 0.0 end]]
        if {[CheckEncoding $text] == 0} {
            return
        }
        set contents [$text get 0.0 end]
        set fhandle [open [file join $folder $file] "w"]
        fconfigure $fhandle -encoding $encode
        puts $fhandle $contents nonewline
        close $fhandle
        
        #UpdateStruct $fullPath
        if {[lindex $files($node) 1] == 1} {
            set files($node) [list [lindex $files($node) 0] 0 [lindex $files($node) 2]]
            $status(active) configure -text [::msgcat::mc "File saved"]
            $nb itemconfigure $node -foreground $color(editTitleNormal)
        }
        UpdateStruct $fullPath $node
    } elseif {$operation == "save_as"} {
        if [info exists activeFile] {
            set node $activeFile
            #set node [$nb raise]
        } else {
            return
        }
        if {$node == "newproj" || $node == "settings" || $node == "about" || $node == ""} {
            return
        }
        if {[info exists files($node)] == 0} {
            return
        }
        set fullPath [lindex $files($node) 0]
        set folder [file dirname $fullPath]
        set file [file tail $fullPath]
        set encode [lindex $files($node) 2] ;# document encoding
        set file [tk_getSaveFile -initialdir $dir(current) -filetypes $types -parent .\
        -initialfile $file -defaultextension .tex]
        if {$file == ""} {return}
        set text "$nb.f$node.f.text"
        set contents [$text get 0.0 end]
        set fhandle [open [file join $folder $file] "w"]
        fconfigure $fhandle -encoding $encode
        
        puts $fhandle $contents nonewline
        close $fhandle
        if {[lindex $files($node) 1] == 1} {
            set files($node) [list [lindex $files($node) 0] 0 $encode]
            $status(active) configure -text [::msgcat::mc "File saved"]
            $nb itemconfigure $node -foreground $color(editTitleNormal)
        }        
        UpdateStruct $fullPath $node
    } elseif {$operation == "save_all"} {
        # SAVE ALL PROCEDURE
        set i 0
        set nodeList [$nb pages 0 end]
        set length [llength $nodeList]
        while {$i < $length} {
            set nbNode [lindex $nodeList $i]
            if {$nbNode != "debug"} {
                set text "$nb.f$nbNode.f.text"
                set savedFile [lindex $files($nbNode) 0]
                set encode [lindex $files($nbNode) 2] ;# document encoding
                set contents [$text get 0.0 end]
                set fhandle [open $savedFile "w"]
                fconfigure $fhandle -encoding $encode
                puts $fhandle $contents nonewline
                close $fhandle
                if {[lindex $files($nbNode) 1] == 1} {
                    set files($nbNode) [list [lindex $files($nbNode) 0] 0 $encode]
                    $status(active) configure -text [::msgcat::mc "File saved"]
                    $nb itemconfigure $nbNode -foreground $color(editTitleNormal)
                }                
            }
            incr i
        }
        Timer "empty" "autosave"
    } elseif {$operation == "close"} {
        set node [$nb raise]
        if {$node == ""} {return}
        if {$node == "debug"} {
            $nb delete $node
            $nb raise [$nb page 0]
            return
        }
        set childrenNode [$tree nodes $node]
        # проверяем есть ли открыте дочерние файлы и закрываем изх если есть
        if {$childrenNode != ""} {
            for {set i 0} {$i <= [llength $childrenNode]} {incr i} {
                if {[info exists files([lindex $childrenNode $i])] == 1} {
                    CloseNode [lindex $childrenNode $i]
                }
            }
        }
        CloseNode $node
    } elseif {$operation == "close_all"} {
        set nodeList [$nb pages 0 end]
        $nb raise [$nb page 0]
        set nbNode [$nb raise]
        while {$nbNode != ""} {
            if {[info exists files($nbNode)] == 1} {
                if {[lindex $files($nbNode) 1] == 1} {
                    set f [lindex $files($nbNode) 0]
                    set f [file tail $f]
                    set answer [tk_messageBox\
                    -message "$f [::msgcat::mc "File was modifyed. Save?"]"\
                    -type yesnocancel -icon warning\
                    -title [::msgcat::mc "Warning"]]
                    case $answer {
                        yes {FileDialog save}
                        no  {}
                        cancel {return}
                    }
                }
            }
            $tree delete $nbNode
            $nb delete $nbNode
            $nb raise [$nb page 0]
            set nbNode [$nb raise]
        }
    } elseif {$operation == "quit_close_all"} {
        set nodeList [$nb pages 0 end]
        $nb raise [$nb page 0]
        set nbNode [$nb raise]
        set fhandle [open [file join $dir(work) bookmarks] "w"]
        while {$nbNode != ""} {
            if {[info exists files($nbNode)] == 1} {
                set f [lindex $files($nbNode) 0]
                puts $f
                # запомнинание открытых файлов и позиций редактирования
                set text "$nb.f$nbNode.f.text"
                puts $fhandle "$f [$text index insert]"
                puts "$f [$text index insert]"
                if {[lindex $files($nbNode) 1] == 1} {
                    set f [file tail $f]
                    set answer [tk_messageBox\
                    -message "$f [::msgcat::mc "File was modifyed. Save?"]"\
                    -type yesnocancel -icon warning\
                    -title [::msgcat::mc "Warning"]]
                    case $answer {
                        yes {FileDialog save}
                        no  {}
                        cancel {return 0}
                    }
                }
            }
            $tree delete $nbNode
            $nb delete $nbNode
            $nb raise [$nb page 0]
            set nbNode [$nb raise]
        }
        close $fhandle
    }
}
proc NewFile {fileName} {
    global dir workDir tree nb font
    destroy .addtoproj
    
    set type [string trim [file extension $fileName] {.}]
    if {$type == "tcl"} {
        set img "tcl"
    } elseif {$type == "tk"} {
        set img "tk"
    } elseif {$type == "txt"} {
        set img "file"
    } elseif {$type == "html"} {
        set img "html"
    } else {
        set img "file"
    }
    #set subNode [InsertTreeNode $fileName $dir(doc)]
    if [info exists dir(current)] {
        set file [file join $dir(current) $fileName]
    } else {
        set file [file join $dir(doc) $fileName]
    }
    
    #puts $file
    #InsertTitle $file $type
    if {[file exists $file] == 0} {
        set fHandle [open "$file" a+]
        close $fHandle
    }
    EditFile $file
}
## ADD FILE INTO PROJECT DIALOG##
proc NewFileDialog {} {
    global dir
    set w .addtoproj
    if {[winfo exists $w]} {
        destroy $w
    }
    # create the new "goto" window
    toplevel $w
    wm title $w [::msgcat::mc "Create new file"]
    wm resizable $w 0 0
    wm transient $w .
    
    frame $w.frmCanv -border 1 -relief sunken
    frame $w.frmBtn -border 1 -relief sunken
    pack $w.frmCanv -side top -fill both -padx 1 -pady 1
    pack $w.frmBtn -side top -fill x
    
    label $w.frmCanv.lblImgTcl -text [::msgcat::mc "Input file name"]
    entry $w.frmCanv.entImgTcl
    pack $w.frmCanv.lblImgTcl $w.frmCanv.entImgTcl -expand true -padx 5 -pady 5 -side top
    
    button $w.frmBtn.btnOk -text [::msgcat::mc "Create"] -relief groove -command {
        NewFile [.addtoproj.frmCanv.entImgTcl get]
    }
    button $w.frmBtn.btnCancel -text [::msgcat::mc "Close"] -command "destroy $w" -relief groove
    pack $w.frmBtn.btnOk $w.frmBtn.btnCancel -padx 2 -pady 2 -fill x -side left
    
    bind $w <Escape> "destroy .addtoproj"
    bind $w.frmCanv.entImgTcl <Return> {
        NewFile [.addtoproj.frmCanv.entImgTcl get]
    }
    focus -force $w.frmCanv.entImgTcl
    $w.frmCanv.entImgTcl insert 0 "name.tex"
}

proc FileAttr {file} {
    global tcl_platform
    set fileAttribute ""
    # get file modify time
    if {$tcl_platform(platform) == "windows"} {
        
    } elseif {$tcl_platform(platform) == "mac"} {
        
    } elseif {$tcl_platform(platform) == "unix"} {
        set unixTime [file mtime $file]
        set modifyTime [clock format $unixTime -format "%d/%m/%Y, %H:%M"]
        append fileAttribute $modifyTime
    }
    # get file size
    set size [file size $file]
    if {$size < 1024} {
        set fileSize "$size b"
    }
    if {$size >= 1024} {
        set s [expr ($size.0) / 1024]
        set dot [string first "\." $s]
        set int [string range $s 0 [expr $dot - 1]]
        set dec [string range $s [expr $dot + 1] [expr $dot + 2]]
        set fileSize "$int.$dec Kb"
    }
    if {$size >= 1048576} {
        set s [expr ($size.0) / 1048576]
        set dot [string first "\." $s]
        set int [string range $s 0 [expr $dot - 1]]
        set dec [string range $s [expr $dot + 1] [expr $dot + 2]]
        set fileSize "$int.$dec Mb"
    }
    append fileAttribute ", $fileSize"
}

## REMOVED SELECTED TEXT INTO FILE AND INCLUDE THEM ##
proc SaveToFile {action} {
    global nb activeFile files dir types typeImage
    set text $nb.f$activeFile.f.text
    set selIndex [$text tag ranges sel]
    if {$selIndex != ""} {
        set posBegin [lindex $selIndex 0]
        set posEnd [lindex $selIndex 1]
        set contents [$text get $posBegin $posEnd]
    } else {
        return
    }
    
    set enc "[lindex $files($activeFile) 2]"
    set contents [encoding convertto $enc $contents]
    set contents [encoding convertfrom $enc $contents]
    
    if {$action == "image"} {
        set file [tk_getSaveFile -initialdir $dir(current) -filetypes $typeImage -parent .\
        -title [::msgcat::mc "Save as"] -initialfile new_name.gif -defaultextension .gif]
        if {$file == ""} {return}
        Render $contents text $file
    } else {
        set file [tk_getSaveFile -initialdir $dir(current) -filetypes $types -parent .\
        -title [::msgcat::mc "Save as"] -initialfile new_name.tex -defaultextension .tex]
        if {$file == ""} {return}
        set fHandle [open $file w]
        puts $fHandle $contents
        close $fHandle
    }
    if {$action == "remove"} {
        $text delete $posBegin $posEnd
        $text insert $posBegin "\n\\input\{[file rootname $file]\}\n"
    }    
    PageRaise $activeFile
}

proc CloseNode {node} {
    global dir font tree nb files treeStruct in lastNode activeFile color status lblList ver sysenc release types
    if {$node == "debug"} {$nb delete $node; $nb raise [$nb page 0]; set node [$nb raise]; return}
    
    if {[info exists files($node)] == 1} {
        if {[lindex $files($node) 1] == 1} {
            set f [lindex $files($node) 0]
            set f [file tail $f]
            set answer [tk_messageBox\
            -message "$f [::msgcat::mc "File was modifyed. Save?"]"\
            -type yesnocancel -icon warning\
            -title [::msgcat::mc "Warning"]]
            case $answer {
                yes {FileDialog save}
                no  {}
                cancel {return}
            }
        }
    }
    PageTab -1
    $nb delete $node
    unset files($node)
    set parentNode [$tree parent $node]
    set curNode [$tree selection get]
    if {[$tree parent $node] == "root"} {
        if {[$tree exists $node] == 1} {
            $tree delete $node
        }
    }
    #$nb raise [$nb page 0]
    #set node [$nb raise]
    ClickTab $node
    $treeStruct delete [$treeStruct nodes root]
    $lblList delete [$lblList item 0 end]
    wm title . "TkLaTeXEditor $ver\($release\)"
    
}











