/**
 * Created by rburson on 2/12/16.
 */
import * as React from 'react'
import {CvState, CvProps, CvBaseMixin, CvEventRegistry, CvEventType, CvStateChangeResult, CvStateChangeType, CvEvent, CvContext, CvMessage, CvMessageType} from './catreact-core'
import {QueryContext, QueryMarkerOption, ObjUtil, Log, ArrayUtil, MenuDef, EntityRec, ActionSource} from 'catavolt-sdk'
import ReactElement = __React.ReactElement;

export interface CvRecordListState extends CvState {
}

export interface CvRecordListProps extends CvProps {
    wrapperElemName?:any;
    wrapperElemProps?:any;
    rowRenderer?:(cvContext:CvContext, entityRecord:EntityRec)=>{}
    queryContext?:QueryContext;
}

/*
 ***************************************************
 * Render a QueryContext
 ***************************************************
 */
export var CvRecordList = React.createClass<CvRecordListProps, CvRecordListState>({

    mixins: [CvBaseMixin],

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

    getDefaultProps: function() {
        return {wrapperElemName: 'span', rowRenderer: null, queryContext: null, wrapperElemProps: {}}
    },
    
    queryContext: function(nextProps) {
        return (nextProps && nextProps.queryContext) || this.props.queryContext || this.firstInScope(QueryContext);
    },

    render: function () {

        const queryContext = this.queryContext();
        if(queryContext && !queryContext.isDestroyed) {
            if(this.props.renderer) {
               return this.props.renderer(this.getChildContext().cvContext);
            } else if (this.props.rowRenderer) {
                const entityRecs:Array<EntityRec> = ArrayUtil.copy<EntityRec>(queryContext.scroller.buffer);
                let newChildren = [];
                entityRecs.forEach((entityRec:EntityRec)=> {
                    const row = this.props.rowRenderer(this.getChildContext().cvContext, entityRec);
                    if(row) {
                        const newElement = React.cloneElement(row, {key: entityRec.objectId});
                        newChildren.push(newElement);
                    }
                });
                return React.createElement(this.props.wrapperElemName, this.props.wrapperElemProps, newChildren);
            } else {
                return null;
            }
        } else {
            return null;
        }
    },

});