######################################################
#                TkTeXEditor
#        Distributed under GNU Public License
# Author: Sergey Kalinin (BanZaj) banzaj@lrn.ru
# Copyright (c) "CONERO lab", 2002, http://conero.lrn.ru
######################################################

######################################################
#                                                    #
# Document structure module (insert\update\deleted   #
#                                                    #
######################################################

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 in(lbl) 0 ;# label cuonter
set in(ref) 0 ;# ref counter
set in(pageref) 0 ;# ref counter
set in(include) 0
set in(input) 0
set in(cite) 0
set in(bibitem) 0
set in(image) 0
set lastPart "root"
set lastChapter "root"
set lastSection "root"
set lastSSection "root"
set lastSSSection "root"
set lastPar "root"
set lastSubPar "root"

## INSERT STRUCT PROCEDURE ##
## reading and parsing string from surce file
## and execute procedures for inserted required structure into structure tree
proc InsertStruct {node line lineNumber fileDir } {
    global tree treeStruct dir font color in lastNode activeFile
    global lastPart lastChapter lastSection lastSSection lastSSSection
    global lastPar lastSubPar lastLabel files nb thumbnail thumb
    #puts $fileDir
    if [regexp -nocase -all -- {(\\part)(\*|)(\[.*?\])*(\{.*?\})} $line struct v1 v1_5 v2 v3] {
        incr in(p)
        InsertNode "part_$in(p)" "root" "[string trimleft [string trimright $v1_5$v3 "\}"] "\{"]" part $lineNumber        
        set lastPart "part_$in(p)"
    }
    if [regexp -nocase -all -- {(\\chapter)(\*|)(\[.*?\])*(\{.*?\})} $line struct v1 v1_5 v2 v3] {
        incr in(c)
        InsertNode "chapter_$in(c)" "$lastPart" "[string trimleft [string trimright $v1_5$v3 "\}"] "\{"]" chapter $lineNumber
        set lastChapter chapter_$in(c)
    }
    if [regexp -nocase -all -- {(\\section)(\*|)(\[.*?\])*(\{.*?\})} $line struct v1 v1_5 v2 v3] {
        incr in(s)
        InsertNode "section_$in(s)" "$lastChapter" "[string trimleft [string trimright $v1_5$v3 "\}"] "\{"]" section $lineNumber
        set lastSection "section_$in(s)"
    }
    if [regexp -nocase -all -- {(\\subsection)(\*|)(\[.*?\])*(\{.*?\})} $line struct v1 v1_5 v2 v3] {
        incr in(ss)
        InsertNode "subsection_$in(ss)" "$lastSection" "[string trimleft [string trimright $v1_5$v3 "\}"] "\{"]" ssection $lineNumber
        set lastSSection "subsection_$in(ss)"
    }
    if [regexp -nocase -all -- {(\\subsubsection)(\*|)(\[.*?\])*(\{.*?\})} $line struct v1 v1_5 v2 v3] {
        incr in(sss)
        InsertNode "subsubsection_$in(sss)" "$lastSSection" "[string trimleft [string trimright $v1_5$v3 "\}"] "\{"]" sssection $lineNumber
        set lastSSSection "subsubsection_$in(sss)"
    }
    if [regexp -nocase -all -- {(\\paragraph)(\*|)(\[.*?\])*(\{.*?\})} $line struct v1 v1_5 v2 v3] {
        incr in(par)
        InsertNode "paragraph_$in(par)" "$lastSSSection" "[string trimleft [string trimright $v1_5$v3 "\}"] "\{"]" paragraph $lineNumber
        set lastPar "paragraph_$in(par)"
    }
    if [regexp -nocase -all -- {(\\subparagraph)(\*|)(\[.*?\])*(\{.*?\})} $line struct v1 v1_5 v2 v3] {
        incr in(spar)
        InsertNode "subparagraph_$in(spar)" "$lastPar" "[string trimleft [string trimright $v1_5$v3 "\}"] "\{"]" subparagraph $lineNumber
        set lastSubPar "subparagraph_$in(spar)"
    }
    if [regexp -nocase -all -- {(\\label)(\{.*?\})} $line struct v1 v2] {
        incr in(lbl)
        InsertLabel "label_$in(lbl)" "$v2" "label"
    }
    if [regexp -nocase -all -- {(\\ref)(\{.*?\})} $line struct v1 v2] {
        incr in(ref)
        InsertRef "ref_$in(ref)" "$v2"
    }
    if [regexp -nocase -all -- {(\\pageref)(\{.*?\})} $line struct v1 v2] {
        incr in(pageref)
        InsertPageref "pageref_$in(pageref)" "$v2"
    }
    if [regexp -nocase -all -- {(\\cite)(\{.*?\})} $line struct v1 v2] {
        incr in(cite)
        InsertLabel "cite_$in(cite)" "$v2" "cite"
    }
    if [regexp -nocase -all -- {(\\bibitem)(\{.*?\})} $line struct v1 v2] {
        incr in(bibitem)
        InsertLabel "bibitem_$in(bibitem)" "$v2" "bibitem"
    }
    
    if { [regexp -nocase -all -- {(\\input)(\{.*?\})} $line struct v1 v2] || [regexp -nocase -all -- {(\\include)(\{.*?\})} $line struct v1 v2] } {
        incr in(input)
        set fullPath [string trimleft [string trimright $v2 "\}"] "\{"]
        set dirName [file dirname $fullPath]
        # извращение 
        if [info exists activeFile] {
            #puts $activeFile
            # set nod $activeFile
            #while {[set parentNode [$tree parent $nod]] != "root"} {set nod $parentNode}
        } else {
            #return
        }
        set rootPath [file dirname [$tree itemcget $node -data]]
        
        set file [file tail $fullPath]
        
        if {$dirName != "."} {
            set dirName [string range $dirName [expr [string first "/" $dirName]+1] end]
            set fileDir [file join $rootPath $dirName]
        } else {
            set fileDir $rootPath
        }
        puts "fullPath - $fullPath\nrootPath - $rootPath\n dirName-$dirName\nfile=$file\nfilrDir-$fileDir"
        set subNode [InsertTreeSubNode "$file" "$activeFile" $fileDir]
        #puts "InsertStruct: node - $subNode\tparent - $node"
        #return
        if [info exists files($subNode)] {
            #puts "$subNode"
            #puts "факин файл [lindex $files($subNode) 0]"
            InsertTreeSubNode $file $node $dirName
            UpdateStruct [lindex $files($subNode) 0] $subNode
        }
        set ext [file extension $file]
        if {$ext == ""} {
            set ext "tex"
        }
        if {[file exists [file join $fileDir $file.$ext]] == 0} {
            $tree itemconfigure $subNode -image [Bitmap::get [file join $dir(img) error.gif]]
        }
    }
    if {[regexp -nocase -all -- {(\\includegraphics)(\{.*?\})} $line struct v1 v2] ==1 || \
    [regexp -nocase -all -- {(\\includegraphics)(\[.*?\])(\{.*?\})} $line struct v1 v3 v2] ==1} {
        if {[string tolower $thumb(show)] == "no"} {
            return
        }
        incr in(image)
        set imagePath [file dirname $v2]
        set rootPath [file dirname [$tree itemcget $node -data]]
        
        if {$imagePath == "."} {
            set fullPathToFile [file join $rootPath [string trimleft [string trimright $v2 "\}"] "\{"]]
        }
        set fullPathToFile [file join $rootPath [string trimleft [string trimright $v2 "\}"] "\{"]]
        set subNode [InsertTreeSubNode [file tail $fullPathToFile] $node [file dirname $fullPathToFile]]
        $tree itemconfigure $subNode -image [Bitmap::get [file join $dir(img) img.gif]]
        
        puts "$imagePath - $rootPath"
        set imgFile [ConvertImage $fullPathToFile]
        if {[info exists thumbnail($imgFile)] == 0} {
            set thumbnail($imgFile) [image create photo -file $imgFile]
            $nb.f$activeFile.f.text image create $lineNumber.end -image $thumbnail($imgFile)
            puts "Image $thumbnail($imgFile) was create"
        } else {
            if [lsearch [$nb.f$activeFile.f.text image names ] $thumbnail($imgFile)] {
                puts "$thumbnail($imgFile) - Image already created"
            } else {
                #$nb.f$activeFile.f.text image create $lineNumber.end -image $thumbnail($imgFile)
            }
            #puts "image - $thumbnail($imgFile)\n lists - [$nb.f$activeFile.f.text image names ]"
        }
    }
}
    ## UPDATE DOCUMENT STRUCTURE PROCEDURE ##
    proc UpdateStruct {file node} {
    #puts $file
    #puts $node
    global tree treeStruct dir font color  lblList files
    global lastPart lastChapter lastSection lastSSection lastSSSection
    global lastPar lastSubPar in nb dir activeFile
    if [info exists files($node)] {
        Timer $file "refresh"
    } else {
        return
    }
    #FileDialog save
    # Сохранение текста во временный файл для обновления структуры
    set dirName [file dirname $file]
    set file [file tail $file]
    set text "$nb.f$node.f.text"
    set contents [$text get 0.0 end]
    set fhandle [open [file join $dir(tmp) $file.bak] "w"]
    puts $fhandle $contents nonewline
    close $fhandle
    
    
    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 in(lbl) 0 ;# label cuonter
    set in(ref) 0 ;# ref counter
    set in(pageref) 0 ;# ref counter
    set in(include) 0
    set in(input) 0
    set in(cite) 0
    set in(bibitem) 0
    set lastPart "root"
    set lastChapter "root"
    set lastSection "root"
    set lastSSection "root"
    set lastSSSection "root"
    set lastPar "root"
    set lastSubPar "root"
    ## check if file was deleted from declaration \input and \include
    ## adding new node into file tree
    #set node $activeFile
    set parentNode [$tree parent $node]
    
    #puts "UpdateStruct: node - $node\tparent - $parentNode"
    
    if [$tree exists $node] {
        $tree delete [$tree nodes $node] ;# delete all info about old structure
    } else {
        set file [file tail [lindex $files($node) 0]]
        set fileDir [file dirname [lindex $files($node) 0]]
        InsertTreeSubNode "$file" $parentNode  $fileDir
    }
    $treeStruct delete [$treeStruct nodes root] ;# delete all info about old structure
    $lblList delete [$lblList item 0 end] ;# deleted all old labels from label list
    set fHandle [open [file join $dir(tmp) $file.bak] "r"]
    set lineNumber 1
    while {[gets $fHandle line]>=0} {
        InsertStruct $node $line $lineNumber $dirName
        incr lineNumber
    }
    unset dirName text contents 
}

proc InsertLabel {node label img} {
    global tree treeStruct  lblList dir
    set label [string trimleft $label "\{"]
    set label [string trimright $label "\}"]
    $lblList insert end $node -text "$label" -image [Bitmap::get [file join $dir(img) $img.gif]]
    unset label
}
proc InsertRef {node label} {
    global tree treeStruct  lblList dir
    set label [string trimleft $label "\{"]
    set label [string trimright $label "\}"]
    $lblList insert end $node -text "$label" -image [Bitmap::get [file join $dir(img) ref.gif]]
    unset label
}
proc InsertPageref {node label} {
    global tree treeStruct lblList dir
    set label [string trimleft $label "\{"]
    set label [string trimright $label "\}"]
    $lblList insert end $node -text "$label" -image [Bitmap::get [file join $dir(img) pageref.gif]]
    unset label
}
proc FindLabel {node} {
    global nb activeFile lblList status
    $lblList selection set $node        
    set t [$lblList itemcget $node -text]
    set text [string range $node 0 [expr [string first "_" $node]-1]]
    set findString "$text\{$t\}"
    set text "$nb.f$activeFile.f.text"
    FindProc $text $findString $activeFile
    $status(pos) configure -text [$text index insert];# cursor position
    unset text t findString
}


















