#@package: rcmp-client-object RcmpClient

#
# Remote Computer Management Protocol (RCMP)
#
# Basic object-tcl client class for building RCMP clients.
#
# karl lehenbauer 10/94
#
# $Id: rcmpc.tcl,v 1.1.1.1 1999/03/31 20:34:38 damon Exp $
#

package require Itcl

itcl_class RcmpClient {

    constructor {config} {
    }

    destructor {
    }

    method configure {config} {
    }

    method disconnect {} {
	if {$fromFP != ""} {
	    catch {close $fromFP}
	    set fromFP ""
	}
	if {$toFP != ""} {
	    catch {close $toFP}
	    set toFP ""
	}
	set connected 0
    }

    method connect {{connectHost ""} {hostIP ""}} {
	disconnect

        if {$connectHost != ""} {set host $connectHost}

	if {$hostIP == ""} {
	    set hostIP $host
	}

	lassign [server_open $hostIP $rcmpPort] fromFP toFP

	if {[send "" onlineMessage] != 2} {
	    disconnect
	    error "connect failed: $onlineMessage"
	}
	set connected 1
    }

    method disk {} {
	if {[send disk response data] != 2} {
	    disconnect
	    error "disk request failed"
	}
	echo $data
	echo $response
    }

    method login {user password} {
	if {[send "USER $user"]  != 3} {
	    disconnect
	    error "error sending user"
	}

	if {[send "PASS $password"] != 2} {
	    disconnect
	    error "error sending password"
	}
    }

    method send {message {responseVar ""} {multilineVar ""}} {
	if {$multilineVar != ""} {
	    upvar $multilineVar multilineResponse
	}

	if {$responseVar != ""} {
	    upvar $responseVar response
	}

	set multilineResponse ""
	set inMultiline 0

	if {$message != ""} {
	    puts $toFP $message
	    flush $toFP
	}

        while 1 {
	    if {[gets $fromFP line] < 0} {
		disconnect
		error "EOF from RCMP server"
	    }
	    set firstChar [cindex $line 0]
	    if {!$inMultiline && $firstChar != 1} {
		set response $line
		return $firstChar
	    }
	    if !$inMultiline {
		if {$firstChar != 1} {
		    disconnect
		    error "protocol failure reading server"
		}
		if {[cindex $line 3] == "-"} {
		    set inMultiline 1
		} else {
		    set multilineResponse $line
		}
	    } else {
		# really should make sure we have three entire digits
		if {[ctype digit [crange $line 0 2]] && [cindex $line 3] == " "} {
		    set inMultiline 0
		    if {$firstChar != 1} {
			set response $line
			return $firstChar
		    }
		} else {
		    lappend multilineResponse $line
		}
	    }
	}
    }

    protected fromFP ""
    protected toFP ""

    protected connected 0
    protected state "new"

    public host
    public rcmpPort 222
}

