package com.wiley.compbooks.brose.chapter7.printing;

import org.omg.CORBA.*;
import com.wiley.compbooks.brose.chapter7.printing.PrinterPackage.*;
import org.omg.CosTradingDynamic.*;

import java.io.*;

class PrinterImpl 
    extends TradingPrinterPOA 
{
    private String[] print_command;
    private String[] queue_command;
    private String printer_name;
    private TypeCode ret_type;

    // constructor
    PrinterImpl (String p_command,
		 String q_command,
		 String name,
		 TypeCode dp_eval_ret_type) {
	
	print_command = new String[3];
        print_command[0] = p_command;
	print_command[1] = "-P" + name;
        queue_command = new String[2];
	queue_command[0] = q_command;
	queue_command[1] = name;

	System.out.println("Print command: " + print_command[0] + " " + print_command[1]);

	System.out.println("Queue command: " + queue_command[0] + " " + queue_command[1]);


	printer_name = name;
	ret_type = dp_eval_ret_type;

    }

    public void print_file (String fn)
	    throws PrinterOffLine
    {
	try {
	    Process p;
	    Runtime run = Runtime.getRuntime();
	    print_command[2] = fn;
	    p = run.exec(print_command);
	}
        catch (java.io.IOException ioe) {
	    System.err.println(ioe);
	    throw new PrinterOffLine();
	}
    }

    public short queue_length()
	throws PrinterOffLine
    {	
	try {
	    short len;
	    Process p;
	    Runtime run = Runtime.getRuntime();
	    p = run.exec(queue_command);

	    // sleep while the queue command produces output
	    Thread.sleep(50);

	    // check the length of the output available

	    String cmd_output = 
                ( new BufferedReader( new InputStreamReader(p.getInputStream()))).readLine();

	    len = ( cmd_output != null ? Short.parseShort( cmd_output ) : 0 ) ;
	    System.out.println("Printer " + printer_name + " queue_len:" + len);
	    return len;
	}
	catch (java.lang.InterruptedException ire) {
	    System.err.println(ire);
	    throw new PrinterOffLine();
	}
	catch (java.io.IOException ioe) {
	    System.err.println(ioe);
	    throw new PrinterOffLine();
	}
    }

    public Any evalDP ( 
    	String name,
	TypeCode returned_type,
	Any extra_info
    ) 
	throws DPEvalFailure 
   {
       System.out.println("Printer " + printer_name + " DPEval");

       if ( !name.equals("queue_len") ) {
	   throw new DPEvalFailure();
       }

       if (! returned_type.equal(ret_type)) {
	   throw new DPEvalFailure();
       }
       
       Any ret_val = _orb().create_any();
       try {
	   ret_val.insert_short(this.queue_length());
       }
       catch (PrinterOffLine pol) {
	   throw new DPEvalFailure();
       }
       
       return ret_val;
   }
}
