/**
 * This file implements 2 types of menus (basic roll down and tabs), they are implemented as objects given
 */
if (!qcms){
    var qcms = {}
}
qcms.menu = {}
qcms.menu.Common = function (){
    this._format = function (text){
        return text.replace(/(-|_)/g,' ').trim()
    }
    this._open = function (text,uri,_parentId){
        var _domId = text.replace(/ /g,'-')
        var http = HttpClient.instance()
        http.setHeader('dom',_domId)
        http.setHeader('uri',uri)
        http.post(`${qcms.context}/${uri}`,(x)=>{
            //
            // @TODO: In case of an error
            
            var _dom = $(x.responseText)
            if ( $(_dom).attr("id") == null){
                $(_dom).attr("id",_domId)
            }
            if($(`${_parentId} #${_domId}`).length){
                $(`${_parentId} #${_domId}`).remove()
            }
            var _found = qcms.html.hasNode ($(`${_parentId}`),$(_domId))
            if (_found == 0){
                $(`${_parentId}`).children().slideUp('fast',()=>{
                    $(`${_parentId}`).append(_dom)
                    this._finalize(`${_parentId} #${_domId}`)
                    
                })
            }
            

        })
    }  
    this._finalize = function (_id){
        var _script = $(`${_id} script`)
        
        if (_script.lenth > 0){
            _script.each( (_index)=>{
                var _code = $(_script)[_index].text
                eval(_code)
            })
        }
    }
}
qcms.menu.Basic = function (_layout,_outputId,_domId){
    qcms.menu.Common.call(this)
    this._layout = _layout
    this._parentId = _outputId   //-- target of the output

    this.init = function (){}
    this._build = function (_items){
        var _panes = []
        var _context = this._context ;
        var _open = this._open
        var _parentId = this._parentId
        // var _format = this._format
        // var _finalize = this._finalize
        // var _domId = this._domId
        var _me = this ;
      
        _items.forEach(_item=>{
            var _div = jx.dom.get .instance('DIV')
        
            _div.innerHTML = this._format(_item.text)
            
            //
            // We need to check for the override text and see if it goes here
            _div.className = 'active'
            _div.data = _item
            _panes.push(_div)
            $(_div).on('click', function (){
                //
                // how do we process this ...
                if (this.data.type == 'redirect') {
                    window.open(this.data.url,_me._format(this.data.text))
                }else if (this.data.type == 'dialog'){
                        qcms.dialog.show(this.data)

                }else if (this.data.type == 'open'){
                    window.open(this.data.uri,'_self')
                }else{
                        _me._open(_me._format(this.data.text),this.data.uri,_parentId)

                }
                // if(this.data.uri && this.data.type != 'open') {

                //     if (this.data.type == 'dialog') {
                //         qcms.dialog.show(this.data)
                //     }else{
                //         _me._open(_me._format(this.data.text),this.data.uri,_parentId)
                //     }

                // }else{
                    
                //     //
                //     // redirecting 
                //     if (this.data.uri != null){
                //         window.open(this.data.uri,'_self')
                //     }else{
                //         window.open(this.data.url,_format(this.data.text))
                //     }
                // }
            })

    
        })
        return _panes ;
    }

    /**
     * This part builds the menu automatically
     */
    var _names = _layout.order.menu.length > 0 ? _layout.order.menu : Object.keys(_layout.menu)
    _names.forEach ((_name)=>{
        if (_layout.menu[_name]){
        
            var _div = this._build(_layout.menu[_name]) ;
            
            var _sub = jx.dom.get.instance('DIV')
            var _menuItem = jx.dom.get.instance('DIV')
            _menuItem.innerHTML = this._format (_name)
            _sub.className  = 'sub-menu  border-round border '
            _menuItem.className = 'item'
            _div.forEach(_item=>{$(_sub).append(_item) })
            $(_sub).append(_div)
            _menuItem.appendChild(_sub)
            _domId = (_domId == null || $(_domId).length == 0)?'.main .menu' : _domId
            $(`${_domId}`).append(_menuItem)
        }
    })
}

/**
 * Implementing Tab based menu
 */
qcms.menu.Tabs = function (_layout,_outputId,_domId){
    qcms.menu.Common.call(this)  //-- inheriting format and open functions
    this._layout = _layout
    this._parentId = _outputId   //-- target of the output
    this._domId = _domId
    this.tabs = jx.dom.get.instance('DIV')
    this.tabs.className = 'tabs'
    this._context = qcms.context

   
    this._build = function (text,_item,event){
        var text = text.trim().replace(/(_|-)/ig,' ').trim()
        var _context = this._context;
        if (text.match(/\//)){
            text = text.split(/\//g).slice(-1)[0]
        }
        var _button = jx.dom.get.instance('INPUT')
        var _label = jx.dom.get.instance('LABEL')
        _button.type= 'radio'
        _button.id = text+'tab'
        _button.name = 'menu-tabs'
        
        _label.data = {id:text.toLowerCase(),uri:_item[0].uri}
            
        if (this._layout.icon){
            var _icon = jx.dom.get.instance('I')
                _icon.className = this._layout.icons[text]
            $(_label).append(_icon)
        }
        
        text = ' ' + text
            
        $(_label).append(text)
        $(_button).val(text.toLowerCase())
        _label.htmlFor = _button.id
        // var _open = this._open
        // var _parentId = this._parentId
        var _me = this ;
        $(_label).on('click',function (){
            
            // _me._open(this.data.id,this.data.uri,_me._parentId)
            _me._open(_me._format(this.data.text),this.data.uri,_parentId)
        })
        
        return [_button,_label]        
    }
    
    
    var _names = _layout.order.menu.length > 0 ? _layout.order.menu : Object.keys(_layout.menu)
        // Object.keys(_layout.menu).
    var _me = this ;
    var tabs = this.tabs ;
    _names.forEach(function(_text){
            _item = _layout.menu[_text]
            _tabItem = _me._build(_text,_item)
            
            $(tabs).append(_tabItem)
    })
        
    this.tabs.className  = 'tabs'
    $(this._domId).append(this.tabs) 
    $(this._domId).css({'border':'1px solid transparent'})
    $(this._domId).css({'grid-template-columns':'64px auto'})

}

qcms.menu.init = function(_layout){
 if (_layout.order != null){
        if (_layout.order.length == null && _layout.order.menu == null){
            _layout.order = {menu:[]}
            
        }else if (_layout.order.menu == null){
            _layout.order.menu = []
        }
    }else{
        _layout.order = {menu:[]}
    }
    

    var _count = 0
    var _items = 0
    Object.keys(_layout.menu).forEach(_name=>{
        _items += _layout.menu[_name].length
        _count += 1
    })
    
    if (_count == _items){
        var _menuObject = new qcms.menu.Tabs (_layout,'..qcms-main .qcms-content','.qcms-main .qcms-menu')
    }else{
        var _menuObject = new qcms.menu.Basic (_layout,'.qcms-main .qcms-content','.qcms-main .qcms-menu')
    }
    
        
}

//
// backward compatibility ...
if(!menu){
    var menu = {}
}
menu.init = qcms.menu.init