import * as React from 'react'
import {
    CvState,
    CvProps,
    CvBaseMixin,
    CvEventRegistry,
    CvContext
} from './catreact-core'
import {AppContext} from 'catavolt-sdk'

export interface CatavoltPaneState extends CvState {
}

export interface CatavoltPaneProps extends CvProps {
    /**
     * This enables the use of the {@link CvEventRegistry} cache to 'retain' objects
     * retrieved during navigation requests.  This makes it possible to use a browser 'history',
     * by allowing the retrieval of these objects by 'resource id' from the cache.
     */
    enableResourceCaching?:boolean
}

/**
 *  Top-level container for a Catavolt Application
 */
export var CatavoltPane = React.createClass<CatavoltPaneProps, CatavoltPaneState>({

    propTypes: {
        catavolt: React.PropTypes.instanceOf(AppContext),
        enableResourceCaching: React.PropTypes.bool,
        eventRegistry: React.PropTypes.instanceOf(CvEventRegistry),
        /**
         * renderer signature: (cvContext:CvContext, callbackObj?:any)=>{}
         */
        renderer:React.PropTypes.func
    },

    mixins: [CvBaseMixin],

    componentWillMount: function() {
        this.refresh();
    },

    componentWillReceiveProps: function(nextProps:CatavoltPaneProps) {
        this.refresh(nextProps);

    },

    getChildContext: function() {
        return {
            cvContext:
            {
                catavolt: this.catavolt(),
                eventRegistry: this.eventRegistry(),
                scopeCtx: {
                    scopeObj: this.catavolt(),
                    parentScopeCtx: null
                }
            }
        }
    },

    getDefaultProps: function() {
        return {
            catavolt: AppContext.singleton,
            eventRegistry: new CvEventRegistry(),
            enableResourceCaching: false
        }
    },

    getInitialState: function () {
        return {}
    },

    render: function () {
        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;
        }

    },

    refresh: function(nextProps?:CatavoltPaneProps) {
        if(nextProps) {
            this._cachingEnabled(nextProps.enableResourceCaching);
        } else {
            this._cachingEnabled(this.props.enableResourceCaching);
        }
    },

    _cachingEnabled: function(enabled:boolean) {
        if(enabled) {
            this.eventRegistry().enableCache();
        } else {
            this.eventRegistry().disableCache();
        }
    }

});
