/**
 * Created by rburson on 12/23/15.
 */
import * as React from 'react'
import {CvState, CvProps, CvBaseMixin, CvEvent, CvEventRegistry, CvEventType, CvNavigationResult, CvLauncher} from './catreact-core'
import {Workbench, AppWinDef} from 'catavolt-sdk'


export interface CvWorkbenchState extends CvState {
}

export interface CvWorkbenchProps extends CvProps {
    /**
     *  The sdk {Workbench} to display
     */
    workbench?:Workbench;
    /**
     * The sdk {AppWinDef} from which to retrieve the workbench by the given workbenchId
     * Should not be used if the 'workbench' property is provided
     */
    appWinDef?:AppWinDef;
    /**
     * The workbench id to display
     * Should not be used if the 'workbench' property is provided
     */
    workbenchId?:string;
}

/**
 * Render an sdk {Workbench}
 */
export var CvWorkbench = React.createClass<CvWorkbenchProps, CvWorkbenchState>({

    mixins: [CvBaseMixin],

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

    getDefaultProps: function() {
        return {appWinDef: null, workbenchId:null, workbench:null}
    },

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

    render: function () {

        const workbench = this.workbench();
        if (workbench) {
            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;
        }
    },

    workbench: function() {
        if(this.props.workbench) {
            return this.props.workbench;
        } else {
            const appWinDef = this.appWinDef();
            let workbench = null;
            appWinDef.workbenches.some((wb)=> {
                if (wb.workbenchId == this.props.workbenchId) {
                    workbench = wb;
                    return true;
                } else {
                    return false;
                }
            });
            return workbench;
        }
    }

});
