var NS = window['NS'] = function(cfg) {
    if(cfg.consts){
        this.consts = NS.apply(NS.apply({}, this.consts), cfg.consts);
        delete cfg.consts;
    }
    NS.apply(this, cfg);
    this._update = this._update.bind(this);
    this.resize = this.resize.bind(this);
    this.init();
};
NS.apply = function(a,b) {
    for(var k in b){
        a[k] = b[k];
    }
    return a;
};

(function(NS, glob){
    var svgNS = 'http://www.w3.org/2000/svg';

    var setters = {
        cls: function(el) {
            return function(cls) {
                if( el.tagName.toLowerCase() === 'svg' ){
                    el.setAttribute( 'class', cls );
                }else{
                    el.className = D.cls.apply(D, arguments);
                }
            }
        },
        attr: function(el, attrName) {
            return function(val) {
              if(val !== void 0 && val !== false){
                el.setAttribute( attrName, val );
              }else{
                el.removeAttribute(attrName)
              }
            }
        }
    };


    var used = {
        cls: true, className: true, 'class': true,
        attr: true, style: true, renderTo: true,
        prop: true, bind: true,
        on: true, renderto: true
    };
    var fastDomEl = function(type, cfg) {
        cfg = cfg || {};
        var cls = cfg.cls || cfg['class'] || cfg.className,
          style = cfg.style,

          attr = cfg.attr || {},
          prop = cfg.prop,
          on = cfg.on || {},
          renderTo = cfg.renderTo,
          el;
        el = document.createElementNS( svgNS, type );
        el.setAttribute( 'xmlns', svgNS );

        var i, _i, name;

        for(i in cfg)
            if( cfg.hasOwnProperty(i)){
                name = i.toLowerCase();
                if(name in used)
                    continue;

                if(name.substr(0, 2) === 'on'){
                    on[ name.substr( 2 ) ] = cfg[ i ];
                }else{
                    attr[i] = cfg[i];
                }
            }

        if( cls ){
            if(typeof cls === 'function'){
                cls(setters.cls(el));
            }else if(typeof cls === 'object'){
            }else{
                setters.cls(el)(cls);
            }
        }
        for( i in attr ){
            if(attr.hasOwnProperty( i )){
                setters.attr( el, i )( attr[ i ] );
            }
        }
        for( i in prop ){
            prop.hasOwnProperty( i ) && ( el[ i ] = prop[ i ] );
        }

        for( i in on ){
            on.hasOwnProperty( i ) && el.addEventListener( i, on[ i ] );
        }
        if( style ){
            NS.apply( el.style, style );
        }
        for( i = 2, _i = arguments.length; i < _i; i++ ){
            var child = arguments[ i ];
            D.appendChild( el, child );
        }

        if( renderTo ){
            D.appendChild( renderTo, el );
        }
        return el;

    };
// ~jsx h function
    var domEl = function( type, cfg ){

        if(typeof type === 'function'){
            return type(cfg, [].slice.call(arguments, 2));
        }
        if(typeof type === 'object' && type.hook){
            return type.hook(cfg, [].slice.call(arguments, 2));
        }
        cfg = cfg || {};
        var cls = cfg.cls || cfg['class'] || cfg.className,
            style = cfg.style,

            attr = cfg.attr || {},
            prop = cfg.prop,
            on = cfg.on || {},
            renderTo = cfg.renderTo,
            el = cfg.el || document.createElement( type ),
            classList = el.classList;

        var i, _i, name;

        for(i in cfg)
            if( cfg.hasOwnProperty(i)){
                name = i.toLowerCase();
                if(name in used)
                    continue;

                if(name.substr(0, 2) === 'on'){
                    on[ name.substr( 2 ) ] = cfg[ i ];
                }else{
                    attr[i] = cfg[i];
                }

            }

        if( cls ){
            if(typeof cls === 'function'){
                cls(setters.cls(el));
            }else if(typeof cls === 'object' && cls.hook){
                cls.hook(setters.cls(el));
            }else if(typeof cls === 'object'){
                var resolvedCls = D.cls(cls);
                if(typeof resolvedCls === 'function'){
                    resolvedCls(setters.cls(el));
                }else{
                    setters.cls(el)(resolvedCls);
                }
            }else{
                setters.cls(el)(cls);
            }
        }

        if( style ){
            NS.apply( el.style, style );
        }

        for( i in attr ){
            if(attr.hasOwnProperty( i )){
                if( typeof attr[ i ] === 'function' ){
                    attr[ i ]( setters.attr( el, i ) );
                }else if(typeof attr[ i ] === 'object'&& attr[ i ] !== null && attr[ i ].hook){
                    return attr[ i ].hook(setters.attr(el, i));
                }else{
                    setters.attr( el, i )( attr[ i ] );
                }
            }
        }

        for( i in prop ){
            prop.hasOwnProperty( i ) && ( el[ i ] = prop[ i ] );
        }

        for( i in on ){
            on.hasOwnProperty( i ) && el.addEventListener( i, on[ i ] );
        }

        for( i = 2, _i = arguments.length; i < _i; i++ ){
            var child = arguments[ i ];
            D.appendChild( el, child );
        }

        if( renderTo ){
            D.appendChild( renderTo, el );
        }

        return el;
    };

    var D = NS.D = {
        svg: null,
        label: null,
        div: null,
        span: null,
        path: null,
        canvas: null,
        input: null,
        textarea: null,
        tBody: null,
        tHead: null,
        th: null,
        td: null,
        tr: null,
        Text: function( val ){ return document.createTextNode( val );}
    };
    'div,template,span,input,label,canvas,span,textarea,table,tr,td,th,tBody,tHead'.split( ',' ).forEach( function( name ){
        D[ name ] = function(){
            return domEl.apply( null, [ name ].concat([].slice.call(arguments)))
        };
    } );

    'svg,path,circle'.split( ',' ).forEach( function( name ){
        D[ name ] = function( cfg){
            if( !cfg ){
                cfg = {};
            }
            cfg.el = document.createElementNS( svgNS, name );
            cfg.el.setAttribute( 'xmlns', svgNS );
            return domEl.apply( null, [ null ].concat([].slice.call(arguments)))
        };
    } );

    D.html = function(cfg){
      var el = domEl('div', cfg);
      el.innerHTML =  [].slice.call(arguments,1).join('\n');
      return el;
    };
    D.h = domEl;
    D.s = fastDomEl;
    D.f = function(cfg, children) {
        return children;
    };
    D.removeChildren = function(el){
        var subEl;
        while((subEl = el.lastChild)){
            el.removeChild(subEl);
        }
    };

    D.appendChild = function(el, subEl){
        var type = typeof subEl;

        if(subEl === null){
            return ;
        }
        if( type !== 'object' ){
            // TODO : add hook
            if( type === 'function' ){
                var tmp = D.Text('');//( {cls: 'zero-wrapper'} );
                el.appendChild( tmp );
                var list = [];
                subEl( function(){
// TODO: append 2 TextNodes and remove children between them
                    for( var i = 0, _i = list.length; i < _i; i++ ){
                        list[ i ].parentNode === el && el.removeChild( list[ i ] );
                    }
                    var fragment = document.createDocumentFragment();
                    D.appendChild( fragment, [].slice.call( arguments ) );
                    list = [].slice.call(fragment.childNodes);
                    el.insertBefore(fragment, tmp);
                } )
            }else if( subEl !== void 0 && subEl !== false && subEl !== null ){
                el.appendChild( D.Text( subEl ) );
            }
        }else if('dom' in subEl){
            el.appendChild( subEl.dom );
        }else if( Array.isArray(subEl) ){
            subEl.forEach(subEl => D.appendChild( el, subEl ) );
        }else{
            el.appendChild( subEl );
        }
    };
    D.join = function(arr, delimiter){
        var out = [], isFn = typeof delimiter === 'function';

        for( var i = 0, _i = arr.length - 1; i < _i; i++ ){
            out.push(arr[i], isFn?delimiter(i):delimiter);
        }
        if(i < _i+1)
            out.push(arr[i]);
        return out;
    };

    var dpID = 1;
    var DataPiece = function(id){this.id = id;};
    DataPiece.prototype = {value: void 0, update: function(){}};
    var DataPieceFactory = function(refs, fn, scope) {
        var id = dpID++;
        var dp = new DataPiece(id);
        refs.push(dp);
        fn.call(scope, function(val) {
            dp.value = val;
            dp.update();
        });
        return dp;
    };
    var RefHash = function(){};RefHash.prototype = {any: false};
    D.__cls = function(args, refs) {
        return function(update) {
            var i, _i, lastCls,
              constructCls = function() {
                  var cls = D._cls(args, [], 0);
                  if(lastCls !== cls)
                      update(lastCls = cls);
              };
            for( i = 0, _i = refs.length; i < _i; i++ )
                refs[ i ].update = constructCls;

            constructCls();
        };
    };
    D._cls = function(args, refs, depth) {
        var out = [], i = 0, _i = args.length, token, tmp, key;

        for(;i<_i;i++){
            token = args[i];
            if(typeof token === 'string' && token){
                out.push( token );
            }else if(typeof token === 'object'){
                if(token instanceof DataPiece){
                    token.value && out.push( token.value );
                }else if ( token.hook ){
                    args[i] = DataPieceFactory(refs, token.hook, token);
                }else if(Array.isArray(token)){
                    tmp = D._cls(token, refs, depth+1);
                    // TODO check for push tmp
                    tmp && out.push( token );
                }else{
                    for(key in token){
                        if(token[key] instanceof DataPiece){
                            token[key].value && out.push(key);
                        }else if(typeof token[key] === 'function'){
                            token[ key ] = DataPieceFactory(refs, token[ key ]);
                        }else if(typeof token[key] === 'object' && token[key].hook){
                            token[key] = DataPieceFactory(refs, token[ key ].hook, token[key])
                        }else{
                            token[ key ] && out.push( key );
                        }
                    }
                }
            }else if(typeof token === 'function'){
                args[i] = DataPieceFactory(refs, args[i]);
            }
        }
        return depth === 0 && refs.length ? D.__cls(args, refs): out.join(' ');
    };
    D.cls = function() {
        return D._cls(arguments, [], 0);
    };

    D.escapeCls = function(cls) {
        return (cls+'').replace(/[^a-zA-Z0-9\-_]/g,'');
    };

    var _construct = function(ctor, cfg, p) {
        //if it is not an arrow function
        if('prototype' in ctor && ctor.prototype.constructor === ctor){
            var cls = new ctor(cfg || {}, p);
            return 'dom' in cls ? cls.dom : cls;
        }else{
            return ctor(cfg || {}, p);
        }
    };

    var usage = {};
    var populate = function(name, construct) {
        var tokens = name.split('.'),
          last = tokens.pop(),
          first = tokens.shift();

        // ES 6 consts are not in global scope. So we can not just add vars to window
        var pointer = first?
          new Function('glob', 'return typeof '+first+' !== "undefined"?'+first+':(glob["'+first+'"] = {})')(glob)
          :glob;

        tokens.reduce(function(pointer, token, i, full) {
            return pointer[token] || (pointer[token] = {});
        }, pointer)[last] = construct;

        return construct;
    };
    D.declare = function(name, ctor) {
        var uses;
        if(name in usage){
            log('updated', `${name} (${usage[name].instances.length})`)

            usage[ name ].ctor = ctor;
            uses = usage[ name ].instances;
            for( var i = 0, _i = uses.length; i < _i; i++ ){
                var u = uses[ i ], d = u.dom;
                u.dom = _construct(ctor, u.cfg, u.p);
                if(d.parentNode){
                    d.parentNode.replaceChild( u.dom, d )
                }
            }
        }else{

            log('declared', `${name}`);
            uses = (usage[ name ] = {ctor: ctor, instances: []}).instances;
        }
        return populate(name, function construct (cfg, p) {
            var dom = _construct(ctor, cfg, p);
            uses.push({dom: dom, cfg: cfg, p: p});
            return dom;
        });
    };
    var _log = [], later = false,
        realLog = function() {
            later = false;
            var aggregated = _log.reduce(function(s, item) {
                (s[item.evt] || (s[item.evt] = [])).push(item);
                return s;
            }, {});
            _log.length = 0;
            for(var evt in aggregated){
                console.log('DOM:'+evt+' → '+aggregated[evt].map(function(item) {
                    return item.args.join(' ');
                }).join(', '));
            }
        };
    var log = function(evt) {
        _log.push({type: 'log', evt: evt, args: [].slice.call(arguments, 1)});
        if(!later)
            later = setTimeout(realLog, 1000);

    };


})(window['NS'], typeof window !== "undefined" ? window :
  typeof WorkerGlobalScope !== "undefined" ? self :
    typeof global !== "undefined" ? global :
    typeof GLOBAL !== "undefined" ? GLOBAL :
      Function("return this;")());

var D = NS.D,
  div = D.div,
  span = D.span,
  view = {
      page: {},
      cmp: {}
  };
