package com.eactive.eai.adapter.socket2.tool.admin;

import com.eactive.eai.adapter.socket2.common.SimpleFuture;
import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.config.SocketAdapterFactory;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.Parser;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

public class Shell {
    static String welcomeMsg = "\nNetAdmin: Release 2.0 - Production on " + (new Date()).toString() + "\n"
                             + "Copyright (c) KB.  All rights reserved.\n\n"
                             + "Socket Adapter Administration System v2.0";
    static String byeMsg = "\nBye!\nSocket Adapter Administration System v2.0";
    static String prompt;
    static String context = "";
    
    String hostname;
    int port;
    //NETAdmin session = new NETAdmin();
    ISocketAdapter admin;

    //CommandLineParser parser;
    Parser parser;
    Options options;
    
    public Shell(String hostname, int port) throws Exception {
        // set hostname:port
        this.hostname = hostname;
        this.port = port;
        
        // set prompt
        prompt = "\nnetadmin-" + hostname + ":" + port + "| " + context + "> ";

        /**
         * create socket adapter
         */
		SocketAdapterContext adminContext = new SocketAdapterContext();
		adminContext.setProtocol("FIXED_LENGTH_HEADER");
		adminContext.setAdapterGroupName("AdminAdapterGroup");
		adminContext.setAdapterName("AdminAdapter");
		adminContext.setBoundUsage("IOBOUND");
		adminContext.setSocketType("CLIENT");
		adminContext.setHostName(hostname);
		adminContext.setPortNumber(port);
		adminContext.setAckSupport("N");
		adminContext.setLlFieldType("BIN");
		adminContext.setLlFieldLength(4);
		adminContext.setResponseType("SYNC");
		adminContext.setTimeout(10);
		adminContext.setMaxConnection(1);
		adminContext.setPermanent("Y");
		adminContext.setTraceLevel(adminContext.TRACE_LEVEL_DEFAULT);
		admin = SocketAdapterFactory.createSocketAdapter(adminContext);
		SimpleFuture future = admin.start();
		Object o = future.join(60000L);
		if (o instanceof Exception)
			throw (Exception) o;
    }

    public void loop() throws Exception  {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // System.out.println(welcomeMsg);
        do {
            // set prompt
            prompt = "\nnetadmin-" + hostname + ":" + port + "| " + context + "> ";
            System.out.print(prompt);
            String line = in.readLine();
            
            try {
                if(line != null) process(line);
            } catch(Exception e) {
                // System.out.println("loop error "+ e.toString());
            }
        } while(true);           
    }
    
    public void process(String line) throws Exception {
    	if (line.trim().matches("[ ]*")) {
    		return;
    	} else if (line.trim().matches("(exit|quit|bye)")) {
    		try {
	    		SimpleFuture future = admin.stop();
	    		future.join();
    		} catch(Exception e) {
    			// System.out.println("stop error");
    		}
    		// System.out.println(byeMsg);
    		System.exit(1);
    	}    		
    	
    	byte[] response = (byte[]) admin.sendMessage(line.getBytes());
		if (line.trim().startsWith("cc") || line.trim().startsWith("cd")) {
			String res = new String(response);
			if ("..".equals(context) || "/".equals(context)) {
				context = "";
			} else if (res.trim().startsWith("usage") || res.trim().startsWith("ERROR")) {		
			} else {
				context = res;
			}
		}
		// System.out.println(new String(response));
    }
}
