import { _flattenChildren } from "./createElement";
import { cloneElement } from "./cloneElement";
export const Children = {
    only(children) {
    //only方法接受的参数只能是一个对象，不能是多个对象（数组）。
        if (Array.isArray(children)) {
            children = children[0];
        }
        if (children && children.vtype) {
            return children;
        }
        throw new Error("expect only one child");
    },
    count(children) {
        return _flattenChildren(children, false).length;
    },
    map(children, callback, context) {
        var ret = [];
        _flattenChildren(children, false).forEach(function(el, index) {
            var old = el;
            el = callback.call(context, el, index);
            if (el === null) {
                return;
            }
            if (el.vtype) {
                //如果返回的el等于old,还需要使用原来的key, _prefix
                let curKey = el && el.key !== null ? el.key: null;
                let oldKey = old && old.key !== null ? old.key: null;
                let oldFix = old && old._prefix, key;
                if(oldKey && curKey){
                    //如果新旧虚拟DOM都有key,中间加上"/.$"
                    if(oldKey !== curKey){
                        key += "/.$"+ oldKey;
                    }else{
                        key = ".$" + curKey;
                    }
                }else if(!oldKey && curKey){
                    key +=  ".$" + curKey;
                }else if(oldKey && !curKey){
                    key =  (oldFix + "$" + oldKey).replace(/\d+\$/, "$");
                }else if(!oldKey && !curKey){
                    key =  oldFix; 
                }
                ret.push(cloneElement(el, { key }));
            } else if (el.type) {
                ret.push(Object.assign({}, el));
            } else {
                ret.push(el);
            }
        });
        return ret;
    },
    forEach(children, callback, context) {
        _flattenChildren(children, false).forEach(callback, context);
    },

    toArray: function(children) {
        return _flattenChildren(children, false);
    }
};
