/*
 * CommandMenuItem.java
 *
 * Created on 19 Ноябрь 2009 г., 19:21
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package fptrtest;

/**
 *
 * @author V.Kravtsov
 */

import java.io.*;
import com.shtrih.fiscalprinter.*;
import com.shtrih.fiscalprinter.command.*;

public class CommandMenuItem implements MenuItemInterface
{
    private final ConsoleUtil console;
    private final FlexCommand command;
    private final ShtrihFiscalPrinter printer;
    
    /** Creates a new instance of CommandMenuItem */
    public CommandMenuItem(
        ConsoleUtil console,
        FlexCommand command,
        ShtrihFiscalPrinter printer){
        this.console = console;
        this.command = command;
        this.printer = printer;
    }
    
    public String getText(){
        return command.getText();
    }
    
    public void execute()
    throws Exception
    {
        console.printSeparator();
        CommandParams inParams = command.getInParams();
        CommandParams outParams = command.getOutParams();
        // read input parameters
        if (inParams.size() > 0)
        {
            System.out.println("Enter command parameters (" + 
                String.valueOf(inParams.size()) + ")");
            for (int i=0;i<inParams.size();i++)
            {
                CommandParam param = inParams.get(i);
                String line = param.getName() + " (" + 
                    param.getTypeName() + ", " + 
                    String.valueOf(param.getSize()) + 
                    
                    //String.valueOf(param.getMin()) + ".." + 
                    //String.valueOf(param.getMax()) + 
                    "): ";
                String paramValue = console.readLine(line);
                param.setValue(paramValue);
            }
        }
        // execute command
        int[] data = new int[1];
        try
        {
            System.out.print("Execute command...");
            printer.directIO(0x1D, data, command);
            System.out.println("OK");
            // show output parameters
            if (outParams.size() > 0)
            {
                System.out.println("Command results:");
                console.printSeparator();
                for (int i=0;i<outParams.size();i++)
                {
                    CommandParam param = outParams.get(i);
                    String line = param.getName() + ": " + param.getValue();
                    System.out.println(line);
                }
                console.printSeparator();
            }
        }
        catch(Exception e)
        {
            System.out.println("ERROR: " + e.getMessage());
        }
        console.readLine("Press ENTER to continue");
    }
    
}
