###
### Copyright (C) 2004 Infopark AG.
###
### this is a wizard that creates news documents from form input data
### provided by the user.
###

if {[app get appName] ne "CM"} {
    return
}

namespace eval createShortNews {
    namespace import ::wizardLib::*

    # config
    variable pageSequenceGerman {enterData_de verifyInput_de\
            enterData_en verifyInput_en}
    variable pageSequenceEnglish {enterData_en verifyInput_en\
            enterData_de verifyInput_de}
    variable newsObjClass "Document"
    variable attributes
    set attributes(imageList) "ip_valueAddImage"
    set attributes(abstract) "ip_abstract"

    # internal state
    variable labels
    variable lang
    variable pageName
    variable errors
    variable params

    # renders the wizard page
    proc render {paramsList args} {
        variable pageSequenceGerman
        variable pageSequenceEnglish
        variable lang
        variable pageName
        variable errors
        variable params

        array unset params
        array set params $paramsList
        set lang [getParam wizard.language]
        if {$lang eq "de"} {
            variable pageSequence $pageSequenceGerman
        } else {
            variable pageSequence $pageSequenceEnglish
        }
        set pageName [getParam wizard.page]
        if {$pageName eq "init"} {
            if {$lang eq "de"} {
                set pageName enterData_de
            } else {
                set pageName enterData_en
            }
        }
        set errors [list]

        switch -exact -- [getParam wizard.button] {
            cancel {
                return
            }
            back {
                set index [lsearch -exact $pageSequence $pageName]
                if {$index != 0} {
                    set pageName [lindex $pageSequence [incr index -1]]
                }
            }
            next {
                set index [lsearch -exact $pageSequence $pageName]
                if {$pageName eq "enterData_de"} {
                    if {[string length [getParam title_de]] == 0} {
                        lappend errors [localize error,missingTitle]
                    }
                    if {[string length [getParam abstract_de]] == 0} {
                        lappend errors [localize error,missingAbstract]
                    }
                    if {[string length [getParam newstext_de]] == 0} {
                        lappend errors [localize error,missingNewstext]
                    }
                }
                if {$pageName eq "enterData_en"} {
                    if {[string length [getParam title_en]] == 0} {
                        lappend errors [localize error,missingTitle]
                    }
                    if {[string length [getParam abstract_en]] == 0} {
                        lappend errors [localize error,missingAbstract]
                    }
                    if {[string length [getParam newstext_en]] == 0} {
                        lappend errors [localize error,missingNewstext]
                    }
                }

                if {[llength $errors] == 0} {
                    set pageName [lindex $pageSequence [incr index 1]]
                }
            }
            execute {
                set title_de [getParam title_de]
                set abstract_de [getParam abstract_de]
                set newstext_de [getParam newstext_de]
                set imageId_de [getParam image_de]

                set title_en [getParam title_en]
                set abstract_en [getParam abstract_en]
                set newstext_en [getParam newstext_en]
                set imageId_en [getParam image_en]


                set newsObjectName [clock format [clock seconds]\
                        -format {%Y%m%d%H%M%S}]
                set newsObjectId_de [createNews $newsObjectName $title_de\
                        $abstract_de $newstext_de $imageId_de "de"]
                set newsObjectId_en [createNews $newsObjectName $title_en\
                        $abstract_en $newstext_en $imageId_en "en"]
                addIpLanguageLink $newsObjectId_de $newsObjectId_en
                set parent_de [obj withId $newsObjectId_de get parent]
                set parent_en [obj withId $newsObjectId_en get parent]
                puts "<npsGuiControl>"
                puts "<npsRefresh identifier='$parent_de' depth='subtree'/>"
                puts "<npsRefresh identifier='$parent_en' depth='subtree'/>"
                puts "<npsSelect identifier='$newsObjectId_de'>"
                puts "</npsGuiControl>"
                return
            }
        }

        switch -exact -- $pageName {
            enterData_de {
                puts [enterDataHtml "de"]
            }
            enterData_en {
                puts [enterDataHtml "en"]
            }
            verifyInput_de {
                puts [verifyInputHtml "de"]
            }
            verifyInput_en {
                puts [verifyInputHtml "en"]
            }
        }
    }

    # produces the html code for the "enterData" page
    proc enterDataHtml {attrLangKey} {
        set selectImageStartPath [::shortNewsDefs::imagesFolder $attrLangKey]

        return [pageHtml [subst -nobackslashes {
            <tr>
                <td class="ovh">[localize inputFieldTitle,title]</td>
                <td class="ov">
                    <input class="text" style="width:40em" type="text"
                            name='title_$attrLangKey' value="[quote [getParam title_$attrLangKey]]" />
                </td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,abstract]</td>
                <td class="ov">
                    <textarea cols='50' rows='3' style="width:40em"
                            name='abstract_$attrLangKey'>[quote [getParam abstract_$attrLangKey]]</textarea>
                </td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,newstext]</td>
                <td class="ov">
                    <textarea cols='50' rows='10' style="width:40em"
                            name='newstext_$attrLangKey'>[quote [getParam newstext_$attrLangKey]]</textarea>
                </td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,image]</td>
                <td class="ov">
                    <npsSelectObject name='image_$attrLangKey' objectTypes='image'
                            startPath='$selectImageStartPath'/>
                </td>
            </tr>
        }]]

    }

    # produces the html code for the "verifyInput" page
    proc verifyInputHtml {attrLangKey} {
        return [pageHtml [subst -nobackslashes { <tr>
                <td class="ovh">[localize inputFieldTitle,title]</td>
                <td class="ov">[quote [getParam title_$attrLangKey]]</td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,abstract]</td>
                <td class="ov">[quote [getParam abstract_$attrLangKey]]</td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,newstext]</td>
                <td class="ov">[quote [getParam newstext_$attrLangKey]]</td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,image]</td>
                <td class="ov">[imagePreviewHtml [getParam image_$attrLangKey]]</td>
            </tr>
        }]]
    }

    # surrounds the html content with some html to make it a complete page
    proc pageHtml {content} {
        variable pageName
        variable errors
        return [subst -nobackslashes {
<npsPage name="$pageName" title="[localize title]">
[::playland::wizardLogo]
<ol style="list-style-position:inside">
    [stepsHtml $pageName]
</ol>
<br style="clear:both"/>
[errorsHtml $errors]
<fieldset>
<legend>[localize subtitle,$pageName]</legend>
<table class="ov">
<col width="20%"><col width="80%">
$content
</table>
</fieldset>
[buttonsHtml $pageName]
</npsPage>
        }]
    }

    # does the actual work, i.e. creates the news document
    proc createNews {newsObjectName title abstract newstext imageId attrLangKey} {
        variable newsObjClass
        variable attributes
        set newsPubId [obj withPath [::shortNewsDefs::newsFolder $attrLangKey] get id]
        set newsId [obj withId $newsPubId create name $newsObjectName\
                objClass $newsObjClass]
        obj withId $newsId editedContent set title $title\
                $attributes(abstract) $abstract blob $newstext
        obj withId $newsId editedContent set ip_isShortNews "yes"
        obj withId $newsId editedContent resolveRefs
        obj withId $newsId editedContent set channels {miscellaneous}
        if {$imageId ne ""} {
            set imagePath [obj withId $imageId get path]
            obj withId $newsId editedContent addLinkTo\
                    attribute $attributes(imageList)\
                    destinationUrl $imagePath
        }
        if {[lsearch [obj withId $newsId get validControlActionKeys] "release"] != -1} {
            obj withId $newsId release
        }
        return $newsId
    }

    # adds a link to other languages (i.e. to the english version)
    proc addIpLanguageLink {source destination} {
        if {![obj withId $source get isEdited]} {
            catch {obj withId $source edit}
        }
        catch {
            obj withId $source editedContent addLinkTo attribute ip_languages\
                    destinationUrl [obj withId $destination get path]
        }
        obj withId $source editedContent resolveRefs
        if {[lsearch [obj withId $source get validControlActionKeys] "release"] != -1} {
            obj withId $source release
        }
    }

    # produces the html code which displays the steps through which the wizards
    # goes. the current step will be highlighted.
    proc stepsHtml {currentPage} {
        variable pageSequenceGerman
        variable pageSequenceEnglish
        variable lang
        if {$lang eq "de"} {
            set pageSequence $pageSequenceGerman
        } else {
            set pageSequence $pageSequenceEnglish
        }
        set html "<br/>"
        set count 1
        foreach page $pageSequence {
            append html "$count. "
            if {$page eq $currentPage} {
                append html "<strong>"
            }
            append html [localize $page]
            if {$page eq $currentPage} {
                append html "</strong>"
            }
            append html "<br/>"
            incr count
        }
        return $html
    }

    # produces the html code for the buttons of the page
    proc buttonsHtml {currentPage} {
        variable pageSequence
        variable pageSequenceGerman
        variable pageSequenceEnglish
        variable lang
        if {$lang eq "de"} {
            set pageSequence $pageSequenceGerman
        } else {
            set pageSequence $pageSequenceEnglish
        }
        set html ""
        if {[lindex $pageSequence 0] ne $currentPage} {
            append html "<npsButton name='back' inButtonArea='true'/>"
        }
        if {[lindex $pageSequence end] ne $currentPage} {
            append html "<npsButton name='next' inButtonArea='true'/>"
        } else {
            append html "<npsButton name='execute' inButtonArea='true'/>"
        }
        append html "<npsButton name='cancel' inButtonArea='true'/>"
        return $html
    }

    proc localize {label} {
        variable labels
        variable lang
        foreach key [list "$lang,$label" "de,$label"] {
            if {[info exists labels($key)]} {
                return $labels($key)
            }
        }
        return $label
    }

    proc initLocalizer {} {
        variable labels
        array set labels {}
        set labels(de,title) "Kurzmitteilung in zwei Sprachen anlegen"
        set labels(en,title) "Create short news message in two languages"
        set labels(de,enterData_de) "Deutsche Texte eingeben und Bild ausw\u00e4hlen"
        set labels(en,enterData_de) "Enter German texts and select an image"
        set labels(de,enterData_en) "Englische Texte eingeben und Bild ausw\u00e4hlen"
        set labels(en,enterData_en) "Enter English texts and select an image"
        set labels(de,assignImage_de) "Der deutschen Mitteilung ein Bild zuordnen"
        set labels(en,assignImage_de) "Assign an image to the German news"
        set labels(de,assignImage_en) "Der englischen Mitteilung ein Bild zuordnen"
        set labels(en,assignImage_en) "Assing an image to the English news"
        set labels(de,verifyInput_de) "Deutsche Texte und das Bild pr\u00fcfen"
        set labels(en,verifyInput_de) "Check German texts and the image"
        set labels(de,verifyInput_en) "Englische Texte und das Bild \u00fcberpr\u00fcfen"
        set labels(en,verifyInput_en) "Check English texts and the image"

        set labels(de,subtitle,enterData_de) $labels(de,enterData_de)
        set labels(en,subtitle,enterData_de) $labels(en,enterData_de)
        set labels(de,subtitle,enterData_en) $labels(de,enterData_en)
        set labels(en,subtitle,enterData_en) $labels(en,enterData_en)
        set labels(de,subtitle,assignImage_de) $labels(de,assignImage_de)
        set labels(en,subtitle,assignImage_de) $labels(en,assignImage_de)
        set labels(de,subtitle,assignImage_en) $labels(de,assignImage_en)
        set labels(en,subtitle,assignImage_en) $labels(en,assignImage_en)
        set labels(de,subtitle,verifyInput_de) $labels(de,verifyInput_de)
        set labels(en,subtitle,verifyInput_de) $labels(en,verifyInput_de)
        set labels(de,subtitle,verifyInput_en) $labels(de,verifyInput_en)
        set labels(en,subtitle,verifyInput_en) $labels(en,verifyInput_en)
        set labels(de,inputFieldTitle,title) "Titel:"
        set labels(en,inputFieldTitle,title) "Title:"
        set labels(de,inputFieldTitle,abstract) "Zusammenfassung:"
        set labels(en,inputFieldTitle,abstract) "Abstract:"
        set labels(de,inputFieldTitle,newstext) "Kurzmitteilungstext:"
        set labels(en,inputFieldTitle,newstext) "Short news text:"
        set labels(de,inputFieldTitle,image) "Bild:"
        set labels(en,inputFieldTitle,image) "Image:"
        set labels(de,error,missingTitle) "Bitte geben Sie einen Titel ein!"
        set labels(en,error,missingTitle) "Please enter a title!"
        set labels(de,error,missingAbstract) "Bitte geben Sie eine Zusammenfassung ein!"
        set labels(en,error,missingAbstract) "Please enter an abstract!"
        set labels(de,error,missingNewstext) "Bitte geben Sie den Kurzmitteilungstext ein!"
        set labels(en,error,missingNewstext) "Please enter a short news text!"
    }

    proc init {} {
        initLocalizer
    }

    init
}
