package com.hubspot.jinjava.tree;

import static org.assertj.core.api.Assertions.assertThat;

import java.nio.charset.StandardCharsets;

import org.junit.Before;
import org.junit.Test;

import com.google.common.base.Throwables;
import com.google.common.io.Resources;
import com.hubspot.jinjava.Jinjava;
import com.hubspot.jinjava.JinjavaConfig;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;

public class TreeParserTest {

  JinjavaInterpreter interpreter;

  @Before
  public void setup() {
    interpreter = new Jinjava().newInterpreter();
  }

  @Test
  public void parseHtmlWithCommentLines() {
    parse("parse/tokenizer/comment-plus.jinja");
    assertThat(interpreter.getErrors()).isEmpty();
  }

  @Test
  public void itStripsRightWhiteSpace() throws Exception {
    String leftSpace = "{% for foo in [1,2,3] -%}\n.{{ foo }}\n{% endfor %}";
    final Node tree = new TreeParser(interpreter, leftSpace).buildTree();
    assertThat(interpreter.render(tree)).isEqualTo(".1\n.2\n.3\n");
  }

  @Test
  public void itStripsLeftWhiteSpace() throws Exception {
    String leftSpace = "{% for foo in [1,2,3] %}\n{{ foo }}.\n{%- endfor %}";
    final Node tree = new TreeParser(interpreter, leftSpace).buildTree();
    assertThat(interpreter.render(tree)).isEqualTo("\n1.\n2.\n3.");
  }

  @Test
  public void itStripsLeftAndRightWhiteSpace() throws Exception {
    String leftSpace = "{% for foo in [1,2,3] -%}\n.{{ foo }}.\n{%- endfor %}";
    final Node tree = new TreeParser(interpreter, leftSpace).buildTree();
    assertThat(interpreter.render(tree)).isEqualTo(".1..2..3.");
  }

  @Test
  public void itPreservesInnerWhiteSpace() throws Exception {
    String leftSpace = "{% for foo in [1,2,3] -%}\nL{% if true %}\n{{ foo }}\n{% endif %}R\n{%- endfor %}";
    final Node tree = new TreeParser(interpreter, leftSpace).buildTree();
    assertThat(interpreter.render(tree)).isEqualTo("L\n1\nRL\n2\nRL\n3\nR");
  }

  @Test
  public void trimAndLstripBlocks() {
    interpreter = new Jinjava(JinjavaConfig.newBuilder().withLstripBlocks(true).withTrimBlocks(true).build()).newInterpreter();

    assertThat(interpreter.render(parse("parse/tokenizer/whitespace-tags.jinja")))
        .isEqualTo("<div>\n"
            + "        yay\n"
            + "</div>\n");
  }

  Node parse(String fixture) {
    try {
      return new TreeParser(interpreter, Resources.toString(
          Resources.getResource(fixture), StandardCharsets.UTF_8)).buildTree();
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }

}

@@ -816,34 +816,36 @@
 o in %5B1,2,3%5D -%25%7D
+ 
 %5Cn
+ 
 .%7B%7B foo %7D%7D%5Cn%7B%25 e
@@ -1120,34 +1120,36 @@
 %5D %25%7D%5Cn%7B%7B foo %7D%7D.
+ 
 %5Cn
+ 
 %7B%25- endfor %25%7D%22;%0A
@@ -1418,18 +1418,20 @@
 2,3%5D -%25%7D
+ 
 %5Cn
+ 
 .%7B%7B foo 
@@ -1433,18 +1433,20 @@
  foo %7D%7D.
+ 
 %5Cn
+ 
 %7B%25- endf

test newlines and spaces