/**
 * Class LexMethod - string representation of a method
 * @author Roman Yedokov
 * modifier return_type method_name(parameters){
 *  body;
 * }
 */

package rmi.rmiSynth.lex;


public class LexMethod extends LexStructure {

  private StringVector throwsEx;    //Vector of thrown exceptions
  private LexParam[] params;        //Parameters
  private LexBody body;         //Method body

  /**
   * Constructor
   */
  public LexMethod() {
    params = new LexParam[0];
    body = new LexBody();
    throwsEx = new StringVector();
  }

  /**
   * Gets parameters
   * @return params
   */
  public LexParam[] getParams() {
    return params;
  }

  /**
   * Sets parameters
   * @param _params Parameters
   */
  public void setParams(LexParam[] _params) {
    params = _params;
  }

  /**
   * Gets 1 parameter
   * @param i Index of parameter
   */
  public LexParam getParam(int i) {
    return params[i];
  }

  /**
   * Gets body
   * @return body
   */
  public LexBody getBody() {
    return body;
  }

  /**
   * Sets body
   * @param _body Body
   */
  public void setBody(LexBody _body) {
    body = _body;
  }

  /**
   * Adds exception
   * @param exName Exception name
   */
  public void addThrow(String exName) {
    throwsEx.add(exName);
  }

  /**
   * Returns true if methods throws any exception
   */
  public boolean ifThrows() {
    return throwsEx.size() > 0 ? true : false;
  }

  /**
   * LexMethod to string
   * @param forClass Class vs interface
   * @param forMain Main method vs all others
   * @return s
   */
  public String toString(boolean forClass, boolean forMain) {
    String s = "";
    boolean withType = true;
    boolean withoutType = false;

    s = s + "\t" + getHeader();
    s = s + "(";
    s = s + paramsToString(withType);
    s = s + ")";
    s = s + (ifThrows() ? " throws " + throwsEx.toCSV() : "");
    if (forClass) {             //Class
      //withType = false;
      s = s + "{\n";
      s = s + "\t\t";
      if (forMain) {
        s = s + getBody().codeToString();
      } else {
        s = s + getBody().toString();
        s = s + "(";
        s = s + paramsToString(withoutType);
        s = s + ");";
      }
      s = s + "\n";
      s = s + "\t}\n";
    } else {                        //Interface
      s = s + ";";
    }
    s = s + "\n";
    return s;

  }

  /**
   * Parameters to string
   * @param withType If we need it with type or not
   * @return s
   */
  public String paramsToString(boolean withType) {
    String s = "";
    for (int i = 0; i < params.length; i++) {
      s = s + " " + params[i].toString(withType) + ",";
    }
    s = s.substring(0, Math.max(s.length() - 1, 0));
    return s;
  }

}