/*=======================================================
 * If.java 
 *
 * "A Tcl like language implementation in Java named APWTCL
 * ((Java) Arnulf's Preferred Web Tcl)"
 *
 * APWTCL If class
 *
 * Released under same BSD license as Tcl.
 * (Tcl BSD license found at <http://www.tcl.tk/software/tcltk/license.html>)
 *
 * Copyright 2012 Arnulf P. Wiedemann
 *
 */

package org.apwtcl.lang.cmd;

import java.util.ArrayList;
import org.apwtcl.lang.Interp;
import org.apwtcl.lang.ApwtclObj;
import org.apwtcl.lang.Token;

public class If extends Token {

  public If() {
  }

  public int ifCmd(Interp interp, ArrayList<ApwtclObj> args) {
print("if called!"+args+"!");
    int idx = 1;
    int retcode;
    int current = 1;
    int falsebody = 0;
    boolean err = false;
    int argc = args.size();

    if (args.size() >= 3) {
      while (true) {
        ArrayList<Integer> bool_ptr = new ArrayList<Integer>();
        int bool;
        /* Far not enough arguments given! */
        if (current >= argc) {
          err = true;
          break;
        }
        if ((retcode = interp.eval_expression.getBoolFromExpr(args.get(current++), bool_ptr)) != OK) {
          return retcode;
        }
        bool = bool_ptr.get(0);
        /* There lacks something, isn't it? */
        if (current >= argc) {
          err = true;
          break;
        }
        if (args.get(current).getString().equals("then")) {
          current++;
        }
        /* Tsk tsk, no then-clause? */
        if (current >= argc) {
          err = true;
          break;
        }
        if (bool > 0) {
          return interp.eval_statement.evalObj(args.get(current));
        }
        /* Ok: no else-clause follows */
        if (++current >= argc) {
          interp.setResult(interp.string_obj_type.newEmptyStringObj("IF_1"));
          return OK;
        }
        falsebody = current++;
        if (args.get(falsebody).getString().equals("else")) {
          /* IIICKS - else-clause isn't last cmd? */
          if (current != argc - 1) {
            err = true;
            break;
          }
          return interp.eval_statement.evalObj(args.get(current));
        } else {
          if (args.get(falsebody).getString().equals("elseif")) {
            /* Ok: elseif follows meaning all the stuff
             * again (how boring...) 
	     */
            continue;
	  } else {
            /* OOPS - else-clause is not last cmd? */
            if (falsebody != argc - 1) {
              err = true;
	      break;
	    }
            return interp.eval_statement.evalObj(args.get(falsebody));
	  }
	}
      }
      if (!err) {
        return OK;
      }
    }
    interp.wrongNumArgs(1, args, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
    return ERROR;
  }

}
