(function(window) {
  'use strict';

  var regex = {
    echo: /{{[\s]*([^}\s]*)[\s]*}}/g,
    for: /[\s]*for[\s]*\(.*\)[\s]*{[\s]*/g,
    if: /[\s]*if[\s]*\(.*\)[\s]*{[\s]*/g,
    close: /^}$/g,
  };

  function Template(template) {
    this.template = template;
    this.html;
  }

  Template.prototype.htmlRender = function(string) {
    const DIV = document.createElement('div');
    DIV.innerHTML = string;
    return DIV.childNodes.item(0);
  };

  Template.prototype.appendTo = function(element, onlyChildrens) {
    element = typeof element === 'string' ? document.querySelector(element) : element;
    if (!onlyChildrens) {
      element.appendChild(this.html);
    } else {
      var clone = this.html.cloneNode(true);
      clone = Array.prototype.slice.call(clone.childNodes);
      for (var i = 0; i < this.html.childNodes.length; i++) {
        element.appendChild(clone[i]);
      }
    }

  };

  Template.prototype.prependTo = function(element, onlyChildrens) {
    element = typeof element === 'string' ? document.querySelector(element) : element;
    var firstChild = element.childNodes[0];
    if (!onlyChildrens) {
      element.insertBefore(this.html, firstChild);
    } else {
      var clone = this.html.cloneNode(true);
      clone = Array.prototype.slice.call(clone.childNodes);
      for (var i = 0; i < this.html.childNodes.length; i++) {
        element.insertBefore(clone[i], firstChild);
      }
    }

  };

  Template.prototype.htmlTo = function(element, onlyChildrens) {
    element = typeof element === 'string' ? document.querySelector(element) : element;

    element.innerHTML = '';
    if (!onlyChildrens) {
      element.appendChild(this.html);
    } else {
      var clone = this.html.cloneNode(true);
      clone = Array.prototype.slice.call(clone.childNodes);
      for (var i = 0; i < this.html.childNodes.length; i++) {
        element.appendChild(clone[i]);
      }
    }

  };

  Template.prototype.render = function(data) {
    var html = '',
      createVars = '',
      template = Array.prototype.concat(this.template);

    for (var dataKey in data) {
      createVars += 'var ' + dataKey + '=' + JSON.stringify(data[dataKey]) + ';';
    }

    for (var i = 0; i < template.length; i++) {
      if (/^[<]/g.test(template[i])) {
        template[i] = "html += '" + template[i] + "';";
      }
    }

    template = String.prototype.concat.apply('', template);

    template = template.replace(regex.echo, function(match, p1) {
      return "' + " + p1 + " + '";
    });

    template = createVars + template;

    eval(template);

    this.html = this.htmlRender(html);

    return this.html;
  };

  window.Template = Template;
})(window);
