/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.dsl;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.hamcrest.Matcher;
import org.junit.Test;

import nz.org.riskscape.rl.TokenTypes;

public class LexingStreamTest {

  LexingStream subject = new LexingStream(Source.anon("foo bar baz"));

  @Test
  public void canConsumeABunchOfCharacters() {
    StringBuffer buffer = new StringBuffer();
    while (!subject.isEof()) {
      buffer.append(subject.next());
    }

    assertThat(subject.next(), equalTo('\0'));
  }

  @Test
  public void canConditionallyConsumeACharacter() throws Exception {
    assertThat(subject.peek(), equalTo('f'));
    // still there
    assertThat(subject.peek(), equalTo('f'));
    // consume it
    assertThat(subject.nextIf('f'), is(true));
    // f is gone, it's been consumed!
    assertThat(subject.peek(), equalTo('o'));
    assertThat(subject.next(), equalTo('o'));
  }

  @Test
  public void canConditionallyConsumeEntireStrings() throws Exception {
    // the resulting location is at that start - useful for building a token
    assertThat(subject.nextIf("foo "), hasProperty("index", equalTo(0)));
    // no match, returns null
    assertThat(subject.nextIf("foo "), nullValue());
    // finish it off
    assertThat(subject.nextIf("bar baz"), hasProperty("index", equalTo(4)));
    assertThat(subject.isEof(), is(true));
  }

  @Test
  public void canConditionallyConsumeACharFromASet() throws Exception {
    assertThat(subject.nextIfOneOf("fo".toCharArray()), equalTo('f'));
    assertThat(subject.nextIfOneOf("fo".toCharArray()), equalTo('o'));
    assertThat(subject.nextIfOneOf("fo".toCharArray()), equalTo('o'));
    // no match - zero char
    assertThat(subject.nextIfOneOf("fo".toCharArray()), equalTo('\0'));
  }

  @Test
  public void canSkipThroughCharacters() throws Exception {
    subject.skipWhile("fo".toCharArray());
    assertThat(subject.getLocation(), hasLocation(3, 1, 4));
  }

  @Test
  public void canTrackLineAndColumnPosition() throws Exception {
    subject = new LexingStream(Source.anon("""
        foo
          bar
          \tbaz
        """));

    assertThat(subject.nextIf("foo"), hasLocation(0, 1, 1));
    eatWhitespace();
    assertThat(subject.nextIf("bar"), hasLocation(6, 2, 3));
    eatWhitespace();
    assertThat(subject.nextIf("baz"), hasLocation(13, 3, 4));
  }

  @Test
  public void canTrackLineAndColumnPositionWindowsLineEndings() throws Exception {
    subject = new LexingStream(Source.anon("""
        foo
          bar
          \tbaz
        """.replaceAll("\n", "\r\n")));

    assertThat(subject.nextIf("foo"), hasLocation(0, 1, 1));
    eatWhitespace();
    assertThat(subject.nextIf("bar"), hasLocation(7, 2, 3));
    eatWhitespace();
    assertThat(subject.nextIf("baz"), hasLocation(15, 3, 4));
  }

  @Test
  public void canTrackLineAndColumnPositionWithHorribleMixOfLineEndings() throws Exception {
    subject = new LexingStream(Source.anon("\n" +
        "foo\r" +
        "  bar\r\n" +
        "  \tbaz"));

    eatWhitespace();
    assertThat(subject.nextIf("foo"), hasLocation(1, 2, 1));
    eatWhitespace();
    assertThat(subject.nextIf("bar"), hasLocation(7, 3, 3));
    eatWhitespace();
    assertThat(subject.nextIf("baz"), hasLocation(15, 4, 4));
  }

  @Test
  public void canBeRewound() throws Exception {
    SourceLocation location = subject.nextIf("foo");

    assertThat(subject.getLocation(), not(equalTo(location)));
    subject.rewind(location);
    assertThat(subject.getLocation(), equalTo(location));

    assertThat(subject.next(), is('f'));
  }

  @Test(expected = IllegalArgumentException.class)
  public void rewindingMustGoBackwards() {
    // make sure moving forward fails - this must be done by consuming chars
    subject.rewind(new SourceLocation(4, 1, 5));
  }

  @Test
  public void canBeUsedToConstructATokenWithAStartLocation() throws Exception {
    SourceLocation sourceLocation = subject.nextIf("foo");
    Token token = subject.newToken(TokenTypes.AND, sourceLocation, "foo");

    assertThat(token, allOf(
        hasProperty("value", equalTo("foo")),
        hasProperty("location", hasLocation(0, 1, 1))
    ));
    assertThat(token.end, equalTo(3));
  }
  @Test
  public void canBeUsedToConstructATokenWithACountOfCharsToConsume() throws Exception {
    Token token = subject.newToken(TokenTypes.AND, 3, "<|-foo-|>");

    assertThat(token, allOf(
        hasProperty("value", equalTo("<|-foo-|>")),
        hasProperty("location", hasLocation(0, 1, 1))
    ));
    assertThat(token.end, equalTo(3));

    // creating the token has advanced the position in the stream
    assertThat(subject.getLocation(), hasLocation(3, 1, 4));
  }

  private void eatWhitespace() {
    while (true) {
      char ch = subject.peek();
      if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
        subject.next();
        continue;
      }

      break;
    }
  }

  private Matcher<SourceLocation> hasLocation(int index, int line, int column) {
    return allOf(
        hasProperty("index", equalTo(index)),
        hasProperty("line", equalTo(line)),
        hasProperty("column", equalTo(column))
    );
  }
}
