/*
 * Copyright  2003-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package net.sf.j3d.ext.org.apache.jsch;

import net.sf.j3d.ext.com.jcraft.jsch.Channel;
import net.sf.j3d.ext.com.jcraft.jsch.ChannelExec;
import net.sf.j3d.ext.com.jcraft.jsch.JSchException;
import net.sf.j3d.ext.com.jcraft.jsch.Session;

import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.text.NumberFormat;

public abstract class AbstractSshMessage {

    private Session session;
    private boolean verbose;

    public AbstractSshMessage(Session session) {
        this(false, session);
    }

    /**
     * @since Ant 1.6.2
     */
    public AbstractSshMessage(boolean verbose, Session session) {
        this.verbose = verbose;
        this.session = session;
    }

    protected Channel openExecChannel(String command) throws JSchException {
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);

        return channel;
    }

    protected void sendAck(OutputStream out) throws IOException {
        byte[] buf = new byte[1];
        buf[0] = 0;
        out.write(buf);
        out.flush();
    }

    /**
     * Reads the response, throws a BuildException if the response
     * indicates an error.
     */
    protected void waitForAck(InputStream in)
        throws IOException, RuntimeException {
        int b = in.read();

        // b may be 0 for success,
        //          1 for error,
        //          2 for fatal error,

        if (b == -1) {
            // didn't receive any response
            throw new RuntimeException("No response from server");
        } else if (b != 0) {
            StringBuffer sb = new StringBuffer();

            int c = in.read();
            while (c > 0 && c != '\n') {
                sb.append((char) c);
                c = in.read();
            }

            if (b == 1) {
                throw new RuntimeException("server indicated an error ("
                                         + sb.toString() + ")");
            } else if (b == 2) {
                throw new RuntimeException("server indicated a fatal error ("
                                         + sb.toString() + ")");
            } else {
                throw new RuntimeException("unknown response, code " + b
                                         + " (" + sb.toString() + ")");
            }
        }
    }

    public abstract void execute() throws IOException, JSchException;

    /**
     * @since Ant 1.6.2
     */
    protected final boolean getVerbose() {
        return verbose;
    }

    /*
     * Track progress every 10% if 100kb < filesize < 1mb. For larger
     * files track progress for every percent transmitted.
     */
    protected final int trackProgress(int filesize, int totalLength, 
                                      int percentTransmitted) {

        int percent = (int) Math.round(Math.floor((totalLength /
                                                   (double)filesize) * 100));

        if (percent > percentTransmitted) {
            if (filesize < 1048576) {
                if (percent % 10 == 0) {
                    if (percent == 100) {
                        System.out.println(" 100%");
                    } else {
                        System.out.print("*");
                    }
                }
            } else {
                if (percent == 50) {
                    System.out.println(" 50%");
                } else if (percent == 100) {
                    System.out.println(" 100%");
                } else {
                    System.out.print(".");
                }
            }
        }

        return percent;
    }

}

