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

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

package require smtp

namespace eval createNewsletter {
    namespace import ::wizardLib::*

    # config
    variable pageSequenceGerman {enterData_de verifyInput_de}
    variable selectImageStartPathGerman /internet/playland/de/ressourcen/images
    variable newsObjClass "Newsletter"
    variable attributes

    set attributes(newsletter_news) "ip_newsletterNews"
    set attributes(newsletter_begin) "ip_newsletterHeader"
    set attributes(newsletter_ende) "ip_newsletterFooter"
    set attributes(newsletter_title) "title"
    set attributes(newsletter_receiver) "ip_newsletterRecipients"
    set attributes(title) "title"

    set newsPub_de /internet/playland/de/presse/newsletter
    set newsKlasse "Document"
    set newsKlasse2 "Publication"
    set presse_pub /internet/playland/de/presse/pressemitteilungen
    set newsForLetter [list]

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

    # renders the wizard page
    proc render {paramsList args} {
        variable pageSequenceGerman
        variable lang
        variable pageName
        variable errors
        variable params
        variable presse_pub
        variable newsKlasse
        variable newsKlasse2
        variable newsPub_de
        variable newsForLetter

        array unset params
        array set params $paramsList
        set lang [getParam wizard.language]

        variable pageSequence $pageSequenceGerman

        set pageName [getParam wizard.page]

        # are there any press releases supposed to appear in a newsletter?
        if {$pageName eq "init"} {

            # look up the already used news from existing newsletters
            set linkedNews [list]
            foreach i [listSubtree $newsPub_de] {
                if {[obj withId $i get objClass] eq "Newsletter"} {
                    foreach link [obj withId $i get ip_newsletterNews] {
                        lappend linkedNews [link withId $link get destination]
                    }
                }
            }

            set newsForLetter [list]
            # compare all news in news-archive with news in newsletters
            foreach i [listSubtree $presse_pub] {
                if {[lsearch $linkedNews $i] != -1} {
                    continue
                }
                set objClass [obj withId $i get objClass]
                if {[lsearch [list $newsKlasse $newsKlasse2] $objClass] == -1} {
                    continue
                }
                if {[obj withId $i get ip_newsletterAllocation] ne "yes"} {
                    continue
                }
                lappend newsForLetter $i
            }
            # if all released news have been used in a newsletter, exit. Otherwise proceed.
            if {0 == [llength $newsForLetter]} {
                set pageName exitPage
            } else {
                set pageName enterData_de
            }
        }
        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 anfangstext_de]] == 0} {
                        lappend errors [localize error,missingAbstract]
                    }
                    if {[string length [getParam newstext_de]] == 0} {
                        lappend errors [localize error,missingNewstext]
                    }
                    if {[string length [getParam newsReceiver_html]] == 0} {
                        lappend errors [localize error,missingReceiver]
                    }
                }
                if {[llength $errors] == 0} {
                    set pageName [lindex $pageSequence [incr index 1]]
                }
            }
            Testmail {
                set comm 0
                set server [::emailNotification::smtpServer]
                if {$server eq ""} {
                    lappend errors [localize error,missingMailhost]
                } else {
                    set userLogin [whoami]
                    set title_de [getParam title_de]
                    set anfangstext_de [getParam anfangstext_de]
                    set newstext_de [getParam newstext_de]
                    set schlusstext_de [getParam schlusstext_de]
                    set newsReceiver_html [getParam newsReceiver_html]

                    set newsObjectName [clock format [clock seconds]\
                            -format {%Y%m%d%H%M%S}]
                    set newsObjectId_de [createLetter $newsObjectName $title_de\
                            $anfangstext_de $newstext_de $schlusstext_de\
                            $newsReceiver_html $comm]

                    emailNotificationCmd "action_release_obj" $newsObjectId_de\
                            $userLogin $userLogin "logText"

                    obj withId $newsObjectId_de delete
                }
            }
            execute {
                set comm 1
                set title_de [getParam title_de]
                set anfangstext_de [getParam anfangstext_de]
                set newstext_de [getParam newstext_de]
                set schlusstext_de [getParam schlusstext_de]
                set newsReceiver_html [getParam newsReceiver_html]

                set newsObjectName [clock format [clock seconds]\
                        -format {%Y%m%d%H%M%S}]
                set newsObjectId_de [createLetter $newsObjectName $title_de\
                        $anfangstext_de $newstext_de $schlusstext_de\
                        $newsReceiver_html $comm]
                set parent_de [obj withId $newsObjectId_de get parent]
                puts "<npsGuiControl>"
                puts "<npsRefresh identifier='$parent_de' depth='subtree'/>"
                puts "<npsSelect identifier='$newsObjectId_de'>"
                puts "</npsGuiControl>"
                return
            }
        }

        switch -exact -- $pageName {
            enterData_de {
                puts [enterDataHtml "de"]
            }
            verifyInput_de {
                puts [verifyInputHtml "de"]
            }
            exitPage {
                puts [exitPageHtml]
            }
        }
    }

    # produces the html code for the "enterData" page
    proc enterDataHtml {attrLangKey} {
        variable selectImageStartPathGerman
        variable newsKlasse
        variable newsKlasse2
        variable newsForLetter
        set htmlCode ""

        set selectImageStartPath $selectImageStartPathGerman

        # create html code for the choice of news
        foreach i $newsForLetter {
            set docPath [obj withId $i get path]
            set exportPath [guiUrl $docPath]
            append htmlCode "<input type='checkbox' name='newstext_de' value='$i'>"
            append htmlCode "<a href='$exportPath/index.html' target=_blank>"
            append htmlCode [obj withId $i get title]
            append htmlCode "</a><br/>"
        }

        # create html code for the choise of receiver groups
        append newsReceiver [attribute withName ip_newsletterRecipients get values]
        set htmlCode3 ""
        foreach i $newsReceiver {
            append htmlCode3 "<option>$i</option>"
        }

        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,anfangstext]</td>
                <td class="ov">
                    <textarea cols='50' rows='3'
                      style="width:40em" name='anfangstext_$attrLangKey'>[quote [getParam anfangstext_$attrLangKey]]</textarea>
                </td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,newstext]</td>
                <td class="ov">
                    $htmlCode
                </td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,schlusstext]</td>
                <td class="ov">
                    <textarea cols='50' rows='3' style="width:40em" name='schlusstext_$attrLangKey'>[quote [getParam schlusstext_$attrLangKey]]</textarea>
                </td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,newsReceiver_html]</td>
                <td class="ov">
                    <select name='newsReceiver_html' multiple>$htmlCode3</select>
                </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,anfangstext]</td>
                <td class="ov">[quote [getParam anfangstext_$attrLangKey]]</td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,newstext]</td>
                <td class="ov"><ol style='list-style-type:decimal'>[splitValue [getParam newstext_de] 0]</ol></td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,schlusstext]</td>
                <td class="ov">[quote [getParam schlusstext_$attrLangKey]]</td>
            </tr>
            <tr>
                <td class="ovh">[localize inputFieldTitle,newsReceiver_html]</td>
                <td class="ov"><ul>[splitValue [getParam newsReceiver_html] 1]</ul>
                </td>
            </tr>
        }]]
    }

    # produces the html code for the "exitPage" page
    proc exitPageHtml {} {
        return [pageHtml [subst {<tr>
                <td class="ovh"></td>
                <td class="ov"><h1>Es kann zur Zeit kein neuer Newsletter erstellt werden.</h1></td>
            </tr>
            <tr>
                <td class="ovh">Grund:</td>
                <td class="ov">Es existiert keine Pressemitteilung im System, die f\u00fcr Newsletter
                freigegeben und noch nicht in einem bestehenden Newsletter verwendet wurde.</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 createLetter {newsObjectName title anfangstext newstext schlusstext newsReceiver comm} {
        variable newsObjClass
        variable attributes
        variable newsPub_de

        set newsPubId [obj withPath $newsPub_de get id]
        set newsId [obj withPath $newsPub_de create name $newsObjectName\
                objClass $newsObjClass]
        obj withId $newsId editedContent set $attributes(newsletter_title) $title\
                $attributes(newsletter_begin) $anfangstext\
                $attributes(newsletter_ende) $schlusstext\
                $attributes(newsletter_receiver) $newsReceiver\
                $attributes(title) $title
        foreach id $newstext {
            obj withId $newsId editedContent addLinkTo attribute\
            $attributes(newsletter_news) destinationUrl [obj withId $id get path]
        }
        obj withId $newsId editedContent resolveRefs
        if {$comm} {
            obj withId $newsId release
        }
        return $newsId
    }

    # 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 lang
        set pageSequence $pageSequenceGerman

        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 lang

        set pageSequence $pageSequenceGerman

        set html ""
        if {[lindex $pageSequence 0] ne $currentPage && $currentPage ne "exitPage"} {
            append html "<npsButton title='Ein Schritt zur\u00fcck' name='back' inButtonArea='true' />"
        }
        if {[lindex $pageSequence end] ne $currentPage && $currentPage ne "exitPage"} {
            append html "<npsButton title='N\u00e4chster Schritt' name='next' inButtonArea='true' />"
        }
        if {[lindex $pageSequence end] eq $currentPage} {
            append html "<npsButton title='Newsletter erstellen und zur Pr\u00fcfung einreichen' name='execute' inButtonArea='true'/>"
        }
        if {$currentPage eq "verifyInput_de"} {
            append html "<npsButton title='Verschickt eine Testmail an den Erzeuger dieses Newsletters' name='Testmail' inButtonArea='true'/>"
        }
        append html "<npsButton title='Wizard beenden' 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) "Newsletter erstellen"
        set labels(en,title) "Create Newsletter"
        set labels(de,enterData_de) "Texte eingeben und gew\u00fcnschte News ausw\u00e4hlen"
        set labels(en,enterData_de) "Enter texts and the desired news"
        set labels(de,verifyInput_de) "Texte pr\u00fcfen"
        set labels(en,verifyInput_de) "Check texts"
        set labels(de,exitPage) "Hinweis"
        set labels(de,subtitle,enterData_de) $labels(de,enterData_de)
        set labels(en,subtitle,enterData_de) $labels(en,enterData_de)
        set labels(de,subtitle,verifyInput_de) $labels(de,verifyInput_de)
        set labels(en,subtitle,verifyInput_de) $labels(en,verifyInput_de)
        set labels(de,subtitle,exitPage) $labels(de,exitPage)
        set labels(de,inputFieldTitle,title) "Titel:"
        set labels(de,inputFieldTitle,anfangstext) "Begr\u00fc\u00dfungstext:"
        set labels(de,inputFieldTitle,newstext) "Auswahl News:"
        set labels(de,inputFieldTitle,schlusstext) "Schlusstext:"
        set labels(de,inputFieldTitle,newsReceiver_html) "Empf\u00e4nger Newsletter:"
        set labels(de,error,missingTitle) "Bitte geben Sie einen Titel ein!"
        set labels(de,error,missingAbstract) "Bitte geben Sie einen Begr\u00fc\u00dfungstext ein!"
        set labels(de,error,missingNewstext) "Bitte w\u00e4hlen Sie mindestens eine News aus!"
        set labels(de,error,missingReceiver) "Bitte w\u00e4hlen Sie mindestens eine Empf\u00e4ngergruppe aus!"
        set labels(de,error,missingMailhost) "Die Funktion 'Testmail versenden' kann nicht ausgef\u00fchrt werden, da kein Mailserver in 'server.xml' eingetragen ist."
    }

    proc init {} {
        initLocalizer
    }


    # splits checkbox-arguments and creates a list
    proc splitValue {value dum} {
        set html ""
        foreach i $value {
            if {$dum == 0} {
                append html "<li>[obj withId $i get title]<br/>"
                append html "[obj withId $i get ip_abstract]</li>"
            }
            if {$dum == 1} {
                append html "<li>$i</li>"
            }
        }
        return $html
    }

    init
}
