/**
 * Created by rburson on 1/14/16.
 */
import * as React from 'react'
import {
    CvState,
    CvProps,
    CvBaseMixin,
    CvEventRegistry,
    CvEvent,
    CvEventType,
    CvNavigationResult,
    CvNavigationResultUtil,
    CvContext
} from './catreact-core'
import {EntityRec, PaneContext, FormContext, ListContext, MenuDef, Prop, ObjUtil} from 'catavolt-sdk'

export interface CvRecordState extends CvState {
}

export interface CvRecordProps extends CvProps {
    entityRec:EntityRec;
    paneContext?:PaneContext;
    renderer?:(cvContext:CvContext)=>{};
    renderPropNames?:Array<string>;
    propRenderer?:(cvContext:CvContext, prop:Prop)=>{};
    wrapperElemName?:string;
    wrapperElemProps?:any;
}

/*
 ***************************************************
 * Render an EntityRec
 ***************************************************
 */
export var CvRecord = React.createClass<CvRecordProps, CvRecordState>({

    mixins: [CvBaseMixin],

    componentDidMount: function () {
    },

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

    getDefaultProps: function () {
        return {
            entityRec: null,
            paneContext: null,
            renderPropNames: null,
            propRenderer: null,
            renderer: null,
            wrapperElemName: 'span',
            wrapperElemProps: {}
        }
    },

    getInitialState: function () {
        return {}
    },

    paneContext: function () {
        return this.props.paneContext || this.findPaneContext();
    },

    render: function () {

        const entityRec = this.props.entityRec;

        if (entityRec) {
            if (this.props.renderer) {
                return this.props.renderer(this.getChildContext().cvContext);
            } else if (this.props.propRenderer) {
                let newChildren = [];
                const renderPropNames = this.props.renderPropNames ? this.props.renderPropNames : entityRec.propNames;
                renderPropNames.forEach((name:string)=> {
                    const prop:Prop = entityRec.propAtName(name);
                    const newElement = React.cloneElement(this.props.propRenderer(this.getChildContext().cvContext, prop), {key: prop.name});
                    newChildren.push(newElement);
                });
                const props = ObjUtil.addAllProps(this.props.wrapperElemProps, {});
                return React.createElement(this.props.wrapperElemName, props, newChildren);
            } else if (React.Children.count(this.props.children) > 0) {
                return this.props.children;
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

});