/*
 * jNPad v0.3 - jNPad's an Simple Text Editor written in Java
 *
 * Copyright (C) 2014-2017  rgs
 *
 * Require JDK 1.6 (or later)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 *
 * Info, Questions, Suggestions & Bugs Report to rgsevero@gmail.com
 */

package jnpad.text.syntax;

import java.awt.Graphics;

import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.Segment;

import jnpad.util.Utilities;

/**
 * The Class SyntaxView.
 * 
 * @version 0.3
 * @since jNPad 0.1
 */
public abstract class SyntaxView extends PlainView2 {
  /**
   * Instantiates a new syntax view.
   *
   * @param elem the elem
   * @param mini the mini
   */
  SyntaxView(Element elem, boolean mini) {
    super(elem, mini);
  }
  
  /**
   * Renders the given range in the model as normal unselected text. Uses the
   * foreground or disabled color to render the text.
   * 
   * @param g the graphics context
   * @param x the starting X coordinate >= 0
   * @param y the starting Y coordinate >= 0
   * @param start the beginning position in the model >= 0
   * @param end the ending position in the model >= 0
   * @return the X location of the end of the range >= 0
   * @throws BadLocationException if the range is invalid
   * @see javax.swing.text.PlainView#drawUnselectedText(java.awt.Graphics, int,
   *      int, int, int)
   */
  @Override
  protected int drawUnselectedText(Graphics g, int x, int y, int start, int end) throws BadLocationException {
    // If there's nothing to show, don't do anything!
    if (start == end)
      return x;

    int length = (end < getDocument().getLength() ? end : getDocument().getLength()) - start;
    return doDrawUnselectedText(g, x, y, start, length);
  }

  /**
   * Renders the given range in the model as selected text. This is implemented
   * to render the text in the color specified in the hosting component. It
   * assumes the highlighter will render the selected background.
   * 
   * @param g the graphics context
   * @param x the starting X coordinate >= 0
   * @param y the starting Y coordinate >= 0
   * @param start the beginning position in the model >= 0
   * @param end the ending position in the model >= 0
   * @return the location of the end of the range
   * @throws BadLocationException if the range is invalid
   * @see javax.swing.text.PlainView#drawSelectedText(java.awt.Graphics, int,
   *      int, int, int)
   */
  @Override
  protected int drawSelectedText(Graphics g, int x, int y, int start, int end) throws BadLocationException {
    // If there's nothing to show, don't do anything!
    if (start == end)
      return x;

    int length = (end < getDocument().getLength() ? end : getDocument().getLength()) - start;
    return doDrawSelectedText(g, x, y, start, length);
  }

  /**
   * Do draw unselected text.
   * 
   * @param g the graphics context
   * @param x the starting X coordinate >= 0
   * @param y the starting Y coordinate >= 0
   * @param start the start
   * @param length the length
   * @return the int
   * @throws BadLocationException if the range is invalid
   */
  abstract int doDrawUnselectedText(Graphics g, int x, int y, int start, int length) throws BadLocationException;

  /**
   * Do draw selected text.
   * 
   * @param g the graphics context
   * @param x the starting X coordinate >= 0
   * @param y the starting Y coordinate >= 0
   * @param start the start
   * @param length the length
   * @return the int
   * @throws BadLocationException the bad location exception
   */
  abstract int doDrawSelectedText(Graphics g, int x, int y, int start, int length) throws BadLocationException;

  /**
   * Draw unselected text_.
   *
   * @param g the graphics context
   * @param x the starting X coordinate >= 0
   * @param y the starting Y coordinate >= 0
   * @param start the start
   * @param end the end
   * @return the X location of the end of the range >= 0
   * @throws BadLocationException if the range is invalid
   */
  int drawUnselectedText_(Graphics g, int x, int y, int start, int end) throws BadLocationException {
    return super.drawUnselectedText(g, x, y, start, end);
  }

  /**
   * Draw selected text_.
   *
   * @param g the graphics context
   * @param x the starting X coordinate >= 0
   * @param y the starting Y coordinate >= 0
   * @param start the start
   * @param end the end
   * @return the int
   * @throws BadLocationException if the range is invalid
   */
  int drawSelectedText_(Graphics g, int x, int y, int start, int end) throws BadLocationException {
    return super.drawSelectedText(g, x, y, start, end);
  }
  
  /**
   * Gets the scheme.
   *
   * @return the scheme
   */
  abstract SyntaxScheme getScheme();

  /**
   * Checks if is operator.
   * 
   * @param c the character
   * @return true, if is operator
   */
  boolean isOperator(char c) {
    for (char bracket : getScheme().getOperators()) {
      if (c == bracket)
        return true;
    }
    return false;
  }

  /**
   * Checks if is bracket.
   * 
   * @param c the character
   * @return true, if is bracket
   */
  boolean isBracket(char c) {
    for (char bracket : getScheme().getBrackets()) {
      if (c == bracket)
        return true;
    }
    return false;
  }

  /**
   * Checks if is string delimiter.
   *
   * @param c the character
   * @return true, if is string delimiter
   */
  boolean isStringDelimiter(char c) {
    for (char delim : getScheme().getStringDelimiters()) {
      if (c == delim)
        return true;
    }
    return false;
  }

  /**
   * Checks if is char delimiter.
   *
   * @param c the character
   * @return true, if is char delimiter
   */
  boolean isCharDelimiter(char c) {
    for (char delim : getScheme().getCharDelimeters()) {
      if (c == delim)
        return true;
    }
    return false;
  }
  
  /**
   * Checks if is single line comment start.
   * 
   * @param s the Segment
   * @param index the index
   * @return true, if is single line comment start
   */
  boolean isSingleLineCommentStart(Segment s, int index) {
    return false;
  }

  /**
   * Checks if is multi line comment start.
   * 
   * @param s the Segment
   * @param index the index
   * @return true, if is multi line comment start
   */
  boolean isMultiLineCommentStart(Segment s, int index) {
    return false;
  }

  /**
   * Checks if is multi line comment end.
   * 
   * @param s the Segment
   * @param index the index
   * @return true, if is multi line comment end
   */
  boolean isMultiLineCommentEnd(Segment s, int index) {
    return false;
  }

  /**
   * Scan identifier.
   * 
   * @param s the Segment
   * @param index the index
   * @return the string
   */
  String scanIdentifier(Segment s, int index) {
    String string = new String(s.array, s.offset, s.count);
    int identifierLength;
    if (!Character.isJavaIdentifierStart(string.charAt(index)))
      return Utilities.EMPTY_STRING;
    for (identifierLength = 1; identifierLength < (string.length() - index); identifierLength++) {
      if (!Character.isJavaIdentifierPart(string.charAt(index + identifierLength)))
        break;
    }
    return string.substring(index, index + identifierLength);
  }

  /**
   * Scan multi line comment.
   * 
   * @param s the Segment
   * @param index the index
   * @return the int
   */
  int scanMultiLineComment(Segment s, int index) {
    return 0;
  }

  /**
   * Scan single line comment.
   * 
   * @param s the Segment
   * @param index the index
   * @return the int
   */
  int scanSingleLineComment(Segment s, int index) {
    int commentLength;
    for (commentLength = 0; commentLength < (s.length() - index); commentLength++) {
      char commentChar = s.charAt(index + commentLength);
      if (commentChar == Utilities.LF)
        break;
    }
    return commentLength;
  }

  /**
   * Scan numeric literal.
   * 
   * @param s the Segment
   * @param index the index
   * @return the string
   */
  String scanNumericLiteral(Segment s, int index) {
    String string = new String(s.array, s.offset, s.count);

    // --------
    if (getScheme().hasCLikeSyntax()) {
      try {
        char[]  buf   = string.toCharArray();
        int     bp    = index;
        boolean flag  = false;
        boolean flag1 = false;
        boolean flag2 = false;

        char ch = buf[bp];
        switch (ch) {
          case '0':
            ch = buf[++bp];
            if (ch == 'x' || ch == 'X') {
              flag = true;
              ch = buf[++bp];
            }
            break;
          case '1':
          case '2':
          case '3':
          case '4':
          case '5':
          case '6':
          case '7':
          case '8':
          case '9':
            ch = buf[++bp];
            break;
          default:
            return jnpad.util.Utilities.EMPTY_STRING;
        }

        do {
          switch (ch) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
              ch = buf[++bp];
              break;
            case 'E':
            case 'e':
              if (flag) {
                ch = buf[++bp];
              }
              else {
                if (flag2)
                  return string.substring(index, bp);
                ch = buf[++bp];
                if (ch == '+' || ch == '-')
                  ch = buf[++bp];
              }
              break;

            case 'D':
            case 'F':
            case 'd':
            case 'f':
              ch = buf[++bp];
              if (!flag)
                return string.substring(index, bp);
              break;

            case 'A':
            case 'B':
            case 'C':
            case 'a':
            case 'b':
            case 'c':
              if (!flag)
                return string.substring(index, bp);
              ch = buf[++bp];
              break;

            case '.':
              if (flag || flag1 || flag2)
                return string.substring(index, bp);
              flag1 = true;
              ch = buf[++bp];
              break;

            case 'L':
            case 'l':
              ch = buf[++bp];
              return string.substring(index, bp);

            default:
              if (Character.isDigit(ch))
                ch = buf[++bp];
              else
                return string.substring(index, bp);
              break;
          }
        } while (true);
      }
      catch (Exception ex) {
        //ignore
      }
    }
    // --------
    
    int identifierLength;
    for (identifierLength = 0; identifierLength < (string.length() - index); identifierLength++) {
      if (!Character.isDigit(string.charAt(index + identifierLength)))
        break;
    }
    return string.substring(index, index + identifierLength);
  }

  /**
   * Scan string literal.
   *
   * @param s the Segment
   * @param index the index
   * @return the int
   */
  int scanStringLiteral(Segment s, int index) {
    int stringLength;
    boolean backslash = false;
    for (stringLength = 1; stringLength < (s.length() - index); stringLength++) {
      char stringChar = s.charAt(index + stringLength);
      if (stringChar == '\\')
        backslash = true;
      else if (stringChar == Utilities.LF)
        break;
      else if (isStringDelimiter(stringChar) && !backslash) {
        stringLength++;
        break;
      }
      else if (backslash)
        backslash = false;
    }
    return stringLength;
  }

  /**
   * Scan char literal.
   *
   * @param s the Segment
   * @param index the index
   * @return the int
   */
  int scanCharLiteral(Segment s, int index) {
    int charLength;
    boolean backslash = false;
    for (charLength = 1; charLength < (s.length() - index); charLength++) {
      char charChar = s.charAt(index + charLength);
      if (charChar == '\\')
        backslash = true;
      else if (charChar == Utilities.LF)
        break;
      else if (isCharDelimiter(charChar) && !backslash) {
        charLength++;
        break;
      }
      else if (backslash)
        backslash = false;
    }
    return charLength;
  }

}
