/**
 * Created by rburson on 3/17/16.
 */
import * as React from 'react'
import {
    CvState,
    CvProps,
    CvBaseMixin,
} from './catreact-core'
import {AppWinDef, Workbench} from 'catavolt-sdk'

export interface CvWorkbenchMenuState extends CvState {
}

export interface CvWorkbenchMenuProps extends CvProps {
    appWinDef?:AppWinDef;
    menuItemRenderer:(workbench:Workbench)=>{}
    wrapperElemName?:string;
    wrapperElemProps?:any;
}

/*
 ***************************************************
 * A component analogous to Catavolt AppWinDef
 ***************************************************
 */
export var CvWorkbenchMenu = React.createClass<CvWorkbenchMenuProps, CvWorkbenchMenuState>({

    mixins: [CvBaseMixin],

    appWinDef: function() {
        return this.props.appWinDef || this.firstInScope(AppWinDef);
    },

    getChildContext: function() {
        const ctx = this.getDefaultChildContext();
        ctx.cvContext.scopeCtx.scopeObj = this.appWinDef();
        return ctx;
    },

    getDefaultProps: function() {
        return {appWindDef:null, menuItemRenderer:null, wrapperElemName:'span', wrapperElemProps:{}};
    },

    render: function () {

        const appWinDef:AppWinDef = this.appWinDef();
        
        if(appWinDef){
            if(this.props.menuItemRenderer) {
                return React.createElement(this.props.wrapperElemName, this.props.wrapperElemProps,
                    appWinDef.workbenches.map((workbench:Workbench)=>{ return this.props.menuItemRenderer(workbench) })) 
            } else if (this.props.renderer) {
                return this.props.renderer(this.getChildContext().cvContext);
            } else if (React.Children.count(this.props.children) > 0) {
                return this.props.children
            } else {
                return null;
            }
        } else {
            return null;
        }
    },

});