/**
 * Created by rburson on 5/28/16.
 */

import * as React from 'react'
import {
    CvState,
    CvProps,
    CvBaseMixin,
    CvEventRegistry,
    CvEvent,
    CvEventType,
    CvContext,
    CvMessage
} from './catreact-core'

export interface CvMessagePaneState extends CvState {
    message:CvMessage;
}

export interface CvMessagePaneProps extends CvProps {
    messageRenderer?:(cvContext:CvContext, message:CvMessage, callback:CvMessagePaneCallback)=>{};
}

export interface CvMessagePaneCallback {
    clear();
}

/*
 ***************************************************
 * Render a Message
 ***************************************************
 */
export var CvMessagePane = React.createClass<CvMessagePaneProps, CvMessagePaneState>({

    mixins: [CvBaseMixin],

    componentDidMount: function () {
        (this.eventRegistry() as CvEventRegistry).subscribe<CvMessage>(this._messageListener, CvEventType.MESSAGE);
    },

    componentWillUnmount: function() {
        (this.eventRegistry() as CvEventRegistry).unsubscribe(this._messageListener);
    },
    
    message: function() {
      return this.state.message;   
    },
    
    getChildContext: function () {
        const ctx = this.getDefaultChildContext();
        ctx.cvContext.scopeCtx.scopeObj = this.message();
        return ctx;
    },

    getDefaultProps: function () {
        return { renderer: null, messageRenderer: null }
    },

    getInitialState: function () {
        return {message: null}
    },

    render: function () {

        const message = this.message();

        if (message) {
            if (this.props.renderer) {
                return this.props.renderer(this.getChildContext().cvContext);
            }else if (this.props.messageRenderer) {
                return this.props.messageRenderer(this.getChildContext().cvContext, message, this._getCallbackObj());
            } else if (React.Children.count(this.props.children) > 0) {
                return this.props.children;
            } else {
                return null;
            }
        } else {
            return null;
        }

    },
    
    _messageListener: function(event:CvEvent<CvMessage>) {
        this.setState({message: event.eventObj});
    },

    _getCallbackObj: function ():CvMessagePaneCallback {

        return { 
            clear: () => {
                this.setState({message: null});         
            }
        };
    }
            

});