/**
 * @category Core
 * @subcategory Application
 * @extends Controller
 */
class MasterController extends Controller {

    content = null;
    
    /**
     * 
     */
    constructor() { 
        super(); 
        if(app.MessageBus) this.onBusEnabled()
    }

    /** 
     * Called on init, if bus enabled (probably not yet connected)
    */
    onBusEnabled() { app.MessageBus.whenConnected(this.onBusConnected.bind(this)) }

    /** Called on bus connection
    * Might be called again upon drop+reconnect
    * Good place to put general subscriptions, to ensure
    * you'll resubscribe after drop+reconnect
    */ 
    onBusConnected(){ }

    /**
     * 
     * @param {*} name 
     * @returns {View}
     */
    useTemplate(name) {          
        let className = name.split('/').pop(0);
        let args = {};
        
        if(name) {
            if(!Controller._template || (Controller._template.name != className)) {
                args.onContentLoaded = this.onTemplateLoaded;
                return(this.loadView(name, args));
            } 
        }
        return(new Promise((resolve) => { resolve(null); }));  
    }    

    /**
     * 
     * @param {*} args 
     * @param {*} data 
     * @param {*} html 
     */
    onTemplateLoaded(args,data, html) {
        let container = document.createElement('div');
        container.innerHTML = html;
        
        this.el = document.body;
        
        this.el.innerHTML = '';

        while(container.children.length > 0) {
            this.el.appendChild(container.children[0]);
        }
        
        let view = new app.LoadedClasses[args.className]();

        Controller._template = {name: args.className, view: view, dom: this.el};
        
        view.el = this.el;
      
        view.DOMContentLoaded();
        this.content = Controller._template.view;
        this.ControllerReady();
    }

    /**
     * 
     */
    ControllerReady() {}
}

app.registerClass('MasterController', MasterController);