/*
 *  Integer Number Arithmetic (+ - * /) services class
 *
 *  2004 - 2011 Frantisek Zboril jr.
 *  Faculty of Information Technology
 *  zborilf@fit.vutbr.cz
 *  http://www.fit.vutbr.cz/~zborilf
 *
 * (C) Brno University of Technology
 * Freeware licence VUT v Brně
 * https://wis.fit.vutbr.cz/FIT/db/dir.php/dr/VZ2007/externiInformace/softwareNaWebu/Priloha2_rozh23.pdf

 */

package jTMass.core.jTMassPlatform.jTServices;

import jTMass.TMass;
import jTMass.core.jALLL.jTObjects.TAtom;
import jTMass.core.jALLL.jTObjects.TFail;
import jTMass.core.jALLL.jTObjects.TList;
import jTMass.core.jALLL.jTObjects.TObject;
import jTMass.core.jTMassPlatform.TPlatform;

public class TSIntegerArithmetic extends TASSynchronousService{

    /* Type semantic, op is + ("p") or - ("m") or * ("k") or / ("d")
     * op((WN)Atom,(WN)Atom) Reg = Atom op Atom
     * op(Atom,Atom) Reg=Fail
     * op(List,Atom) Reg=op(car(List), Atom)
     * op(Atom,List) Reg=op(Atom, car(List))
     * op(List,List) Reg=op(car(List),car(List))
     */

    Integer evaluateOpList(TList oplist) throws NumberFormatException{
        TObject operator, param1, param2;
        Integer n1,n2;
        String opcode;
        operator=getIth(1,oplist);
        param1=getIth(2,oplist);
        param2=getIth(3,oplist);

        if(operator!=null){
            if(param1 instanceof TList)
                n1=evaluateOpList((TList)param1);
            else
                n1=this.objectToInteger(param1);

            if(param2 instanceof TList)
                n2=evaluateOpList((TList)param2);
            else
                n2=this.objectToInteger(param2);

            opcode=operator.getContent();
            if(opcode.contentEquals("p"))
                return(n1+n2);
            if(opcode.contentEquals("m"))
                return(n1-n2);
            if(opcode.contentEquals("k"))
                return(n1*n2);
            if(opcode.contentEquals("d"))
                return(n1/n2);
        }
        throw new NumberFormatException();
    }

    @Override
    public TObject processService(TList parameters, String clientName, String serviceName){
        super.processService(parameters,clientName,serviceName);
        try{
            Integer result=evaluateOpList(parameters);

            return(new TAtom(String.valueOf(result)));
        }
        catch(NumberFormatException e){
                TMass._Terminal.reportError("Wrong number in arithmetic expression");
            }
        
        return(new TFail());
     }

    public TSIntegerArithmetic(TPlatform platform){
        super(platform);
    }
}
