class AssetTreeService {

    boolean transactional = false

    def js = new JavascriptService()

    def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib()

    /** Html class and id settings */

    def buttonHtmlClass() {
        "tree_button"
    }
    def paneHtmlClass() {
        'overlayPane'
    }
    def paneHtmlId() {
        'assetTreePane'
    }
    def paneCloseHtmlClass() {
        'tree_pane_close'
    }
    def tableDivHtmlClass() {
        'tree'
    }
    def tableHtmlId() {
        'assetTreeTable'
    }
    def tableLoadingImgId() {
        'assetTreeLoadingImg'
    }

    /**
    * Build and return the asset tree table.
    * To be used in conjunction with AssetTreeTagLib which inserts the wrapper div.
    * This table replaces the contents of the wrapper div.
    * @returns The asset tree table as a String
    */
    def buildAssetTree(params, session) {

        def sites = Site.list()

        def visibleBranches = session.assetTreeVisibleBranches ? session.assetTreeVisibleBranches.tokenize(',') : []

        def branchStyle = { branchId ->
            if(visibleBranches.contains(branchId))
                ''
            else
                'display:none;'
        }

        def branchImg = { branchId ->
            if(visibleBranches.contains(branchId))
                bulletTreeMinusImg()
            else
                bulletTreePlusImg()
        }

        def divIdCount = 0
        def divId = ''
        def nextDivId = {
            divIdCount++
            divId = 'assetTreeBranch'+divIdCount
        }

        def sw = new StringWriter()
        def mkp = new groovy.xml.MarkupBuilder(sw) //this line will be unnecessary in versions of Grails after version 1.2

        // Offer a site create link if no sites are found.
        if(!sites) {
            mkp.div(class: tableDivHtmlClass()) {

                div(class: paneCloseHtmlClass()) {
                    a( href: js.hrefToggle(paneHtmlId()) ) {
                        img(src: closeImg())
                    }
                }

                table(id: tableHtmlId()) {
                    tr() {
                        td( valign: 'top', class: 'value') {
                            ul() {
                                img(src: treeRootImg(), alt: 'TreeRoot')
                                li() {
                                    a(href: siteCreateLink()) {
                                        img(src: addImg(), alt: 'Add', title: 'Add Site')
                                    }
                                } // li
                            } // ul
                        } // td
                    } // tr
                } // table

                div( class: 'buttons') {
                    span(class: 'button') {
                        input( type: 'button', value: g.message(code: 'default.close.text'), onclick: js.onclickToggle(paneHtmlId()) )
                    }
                } // button div
            } // mkp
            return sw.toString()
        } // if(!sites)


        // The main populated table.
        /// @todo: use a loop for the subItem levels.
        mkp.div(class: tableDivHtmlClass()) {

            div(class: paneCloseHtmlClass()) {
                a( href: hrefHideAndSavePane() ) {
                    img(src: closeImg())
                }
            }

            table(id: tableHtmlId()) {
                tr() {
                    td(valign: 'top', class: 'value') {
                        ul() {
                            img(src: treeRootImg(), alt: 'TreeRoot')
                            for(site in sites.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }) {
                                li() {
                                    if(site.sections) {
                                        a(href: hrefToggleBranch(nextDivId()) ) {
                                            img( src: branchImg(divId), id: divId+'img' )
                                        }
                                    }
                                    else
                                        img(src: dashImg())
                                    a( href: siteShowLink(site.id), onclick: onclickHideAndSavePane() ) {
                                        yieldUnescaped( site.encodeAsHTML() )
                                    }
                                    a(href: sectionCreateLink(site.id), onclick: onclickHideAndSavePane()) {
                                        img(src: addImg(), alt: 'Add', title: 'Add Section')
                                    }
                                }
                                if(site.sections) {
                                    div( id: divId, style: branchStyle(divId) ) {
                                        ul() {
                                            for(section in site.sections.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }) {
                                                li() {
                                                    if(section.assets) {
                                                        a( href: hrefToggleBranch(nextDivId()) ) {
                                                            img(src: branchImg(divId), id: divId+'img' )
                                                        }
                                                    }
                                                    else
                                                        img(src: dashImg())
                                                    a( href: sectionShowLink(section.id), onclick: onclickHideAndSavePane() ) {
                                                        yieldUnescaped( section.encodeAsHTML() )
                                                    }
                                                    a(href: assetCreateLink(section.id), onclick: onclickHideAndSavePane()) {
                                                        img(src: addImg(), alt: 'Add', title: 'Add Asset')
                                                    }
                                                }

                                                if(section.assets) {
                                                    div( id: divId, style: branchStyle(divId) ) {
                                                        ul() {
                                                            for(asset in section.assets.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }) {
                                                                li() {
                                                                    if(asset.assetSubItems) {
                                                                        a( href: hrefToggleBranch(nextDivId()) ) {
                                                                            img(src: branchImg(divId), id: divId+'img' )
                                                                        }
                                                                    }
                                                                    else
                                                                        img(src: dashImg())
                                                                    a( href: assetShowLink(asset.id), onclick: onclickHideAndSavePane() ) {
                                                                        yieldUnescaped( asset.encodeAsHTML() )
                                                                    }
                                                                    a(href: assetSubItemCreateLink(asset.id), onclick: onclickHideAndSavePane()) {
                                                                        img(src: addImg(), alt: 'Add', title: 'Add Sub Item')
                                                                    }
                                                                    a(href: assetCopyLink(asset.id), onclick: onclickHideAndSavePane()) {
                                                                        img(src: copyImg(), alt: 'Add', title: 'Copy Asset')
                                                                    }
                                                                } // li

                                                                if(asset.assetSubItems) {
                                                                    div( id: divId, style: branchStyle(divId) ) {
                                                                        ul() {
                                                                            for(assetSubItemL1 in asset.assetSubItems.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }) {
                                                                                li() {
                                                                                    if(assetSubItemL1.subItems) {
                                                                                        a( href: hrefToggleBranch(nextDivId()) ) {
                                                                                            img(src: branchImg(divId), id: divId+'img' )
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                        img(src: dashImg())
                                                                                    a( href: assetSubItemShowLink(assetSubItemL1.id), onclick: onclickHideAndSavePane() ) {
                                                                                        yieldUnescaped( assetSubItemL1.encodeAsHTML() )
                                                                                    }
                                                                                    a(href: assetSubItemCreateWithParentLink(assetSubItemL1.id), onclick: onclickHideAndSavePane()) {
                                                                                        img(src: addImg(), alt: 'Add', title: 'Add Sub Item')
                                                                                    }
                                                                                } // li

                                                                                if(assetSubItemL1.subItems) {
                                                                                    div( id: divId, style: branchStyle(divId) ) {
                                                                                        ul() {
                                                                                            for(assetSubItemL2 in assetSubItemL1.subItems.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }) {
                                                                                                li() {
                                                                                                    if(assetSubItemL2.subItems) {
                                                                                                        a( href: hrefToggleBranch(nextDivId()) ) {
                                                                                                            img( src: branchImg(divId), id: divId+'img' )
                                                                                                        }
                                                                                                    }
                                                                                                    else
                                                                                                        img(src: dashImg())
                                                                                                    a( href: assetSubItemShowLink(assetSubItemL2.id), onclick: onclickHideAndSavePane() ) {
                                                                                                        yieldUnescaped( assetSubItemL2.encodeAsHTML() )
                                                                                                    }
                                                                                                    a(href: assetSubItemCreateWithParentLink(assetSubItemL2.id), onclick: onclickHideAndSavePane()) {
                                                                                                        img(src: addImg(), alt: 'Add', title: 'Add Sub Item')
                                                                                                    }
                                                                                                } // li

                                                                                                if(assetSubItemL2.subItems) {
                                                                                                    div( id: divId, style: branchStyle(divId) ) {
                                                                                                        ul() {
                                                                                                            for(assetSubItemL3 in assetSubItemL2.subItems.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }) {
                                                                                                                li() {
                                                                                                                    if(assetSubItemL3.subItems) {
                                                                                                                        a( href: hrefToggleBranch(nextDivId()) ) {
                                                                                                                            img( src: branchImg(divId), id: divId+'img' )
                                                                                                                        }
                                                                                                                    }
                                                                                                                    else
                                                                                                                        img(src: dashImg())
                                                                                                                    a( href: assetSubItemShowLink(assetSubItemL3.id), onclick: onclickHideAndSavePane() ) {
                                                                                                                        yieldUnescaped( assetSubItemL3.encodeAsHTML() )
                                                                                                                    }
                                                                                                                    a(href: assetSubItemCreateWithParentLink(assetSubItemL3.id), onclick: onclickHideAndSavePane()) {
                                                                                                                        img(src: addImg(), alt: 'Add', title: 'Add Sub Item')
                                                                                                                    }
                                                                                                                } // li

                                                                                                                if(assetSubItemL3.subItems) {
                                                                                                                    div( id: divId, style: branchStyle(divId) ) {
                                                                                                                        ul() {
                                                                                                                            for(assetSubItemL4 in assetSubItemL3.subItems.sort { p1, p2 -> p1.name.compareToIgnoreCase(p2.name) }) {
                                                                                                                                li() {
            //                                                                                                                         if(assetSubItemL4.subItems) {
            //                                                                                                                             a( href: hrefToggleBranch(nextDivId()) ) {
            //                                                                                                                                 img( src: branchImg(divId), id: divId+'img' )
            //                                                                                                                             }
            //                                                                                                                         }
            //                                                                                                                         else
                                                                                                                                    img(src: dashImg())
                                                                                                                                    a( href: assetSubItemShowLink(assetSubItemL4.id), onclick: onclickHideAndSavePane() ) {
                                                                                                                                        yieldUnescaped( assetSubItemL4.encodeAsHTML() )
                                                                                                                                    }
            //                                                                                                                         a(href: assetSubItemCreateWithParentLink(assetSubItemL4.id), onclick: onclickHideAndSavePane()) {
            //                                                                                                                             img(src: addImg(), alt: 'Add', title: 'Add Sub Item')
            //                                                                                                                         }
                                                                                                                                } // li

                                                                                                                            } // assetSubItemL4
                                                                                                                        } // ul
                                                                                                                    } // div
                                                                                                                } // if(assetSubItemL3.subItems)


                                                                                                            } // assetSubItemL3
                                                                                                        } // ul
                                                                                                    } // div
                                                                                                } // if(assetSubItemL2.subItems)

                                                                                            } // assetSubItemL2
                                                                                        } // ul
                                                                                    } // div
                                                                                } // if(assetSubItemL1.subItems)

                                                                            } // assetSubItemL1
                                                                        } // ul
                                                                    } // div
                                                                } // if(asset.assetSubItems)

                                                            } // assets
                                                        } // ul
                                                    } // div
                                                } // if(section.assets)

                                            } //sections
                                        } // ul
                                    } // div
                                } // if(site.sections)
                            } // sites
                        } // ul
                    } // td
                } // tr
            } // table

            div( class: 'buttons') {
                span(class: 'button') {
                    input( type: 'button', value: g.message(code: 'default.close.text'), onclick: onclickHideAndSavePane() )
                }
            }

        } // mkp

        return sw.toString()

    } // buildAssetTree


    /** Imgs */

    def treeRootImg() {
        g.resource(dir:'images/skin',file:'chart_organisation.png')
    }
    def addImg() {
        g.resource(dir:'images/skin',file:'database_add.png')
    }
    def copyImg() {
        g.resource(dir:'images/skin',file:'page_copy.png')
    }
    def bulletTreePlusImg() {
        g.resource(dir:'images/skin',file:'bullet_tree_plus.png')
    }
    def bulletTreeMinusImg() {
        g.resource(dir:'images/skin',file:'bullet_tree_minus.png')
    }
    def dashImg() {
        g.resource(dir:'images/skin',file:'hline_short.png')
    }
    def closeImg() {
        g.resource(dir:'images/skin',file:'cross.png')
    }

    /** js calls */

    def hrefShowPane() {
        def url = g.createLink(controller: 'assetDetailed', action: 'assetTree')
        'javascript: showAssetTreePane(\"assetTreePane\", \"assetTreeLoadingImg' +'\", \"' + url + '\");'
    }

    def onclickHideAndSavePane() {
        def saveUrl = g.createLink(controller: 'appCore', action: 'saveAssetTreeStatus')
        'return hideAssetTreePane(\"assetTreePane\", \"assetTreeTable' + '\", \"' + saveUrl + '\");'
    }

    def hrefHideAndSavePane() {
        def saveUrl = g.createLink(controller: 'appCore', action: 'saveAssetTreeStatus')
        'javascript: hideAssetTreePane(\"assetTreePane\", \"assetTreeTable' + '\", \"' + saveUrl + '\");'
    }

    def hrefToggleBranch(divId) {
       'javascript: toggleBranch(\"' + divId + '\", \"' + divId + 'img' +'\", \"' + bulletTreeMinusImg() +'\", \"' + bulletTreePlusImg() + '\");'
    }

    /** Links */

    def siteCreateLink() {
        g.createLink(controller: 'siteDetailed', action: 'create').toString()
    }
    def siteShowLink(id) {
        g.createLink(controller: 'siteDetailed', action: 'show', params: ['id': id] ).toString()
    }

    def siteEditLink(id) {
        g.createLink(controller: 'siteDetailed', action: 'edit', params: ['id': id] ).toString()
    }

    def sectionCreateLink(siteId) {
        g.createLink(controller: 'sectionDetailed', action: 'create', params: ['site.id': siteId] ).toString()
    }

    def sectionShowLink(id) {
        g.createLink(controller: 'sectionDetailed', action: 'show', params: ['id': id] ).toString()
    }

    def sectionEditLink(id) {
        g.createLink(controller: 'sectionDetailed', action: 'edit', params: ['id': id] ).toString()
    }

    def assetCreateLink(sectionId) {
        g.createLink(controller: 'assetDetailed', action: 'create', params: ['section.id': sectionId] ).toString()
    }

    def assetShowLink(id) {
        g.createLink(controller: 'assetDetailed', action: 'show', id: id ).toString()
    }

    def assetEditLink(id) {
        g.createLink(controller: 'assetDetailed', action: 'edit', id: id ).toString()
    }

    def assetCopyLink(id) {
        g.createLink(controller: 'assetDetailed', action: 'copy', params: ['assetToCopy.id': id] ).toString()
    }

    def assetSubItemCreateLink(assetId) {
        g.createLink(controller: 'assetSubItemDetailed', action: 'create', params: ['asset.id': assetId] ).toString()
    }

    def assetSubItemCreateWithParentLink(parentItemId) {
        g.createLink(controller: 'assetSubItemDetailed', action: 'create', params: ['parentItem.id': parentItemId] ).toString()
    }

    def assetSubItemShowLink(id) {
        g.createLink(controller: 'assetSubItemDetailed', action: 'show', params: ['id': id] ).toString()
    }

    def assetSubItemEditLink(id) {
        g.createLink(controller: 'assetSubItemDetailed', action: 'edit', params: ['id': id] ).toString()
    }

} // end class