extern crate leek;
extern crate smallvec;

use leek::endpoint::message::{ResponsePartStatus, read_response_part,
                                  write_command};

use smallvec::SmallVec;

use std::env;
use std::error;
use std::io::BufRead;
use std::io;
use std::net::TcpStream;
use std::process;
use std::str;

type Error = Box<'static + error::Error>;

fn main() {
    safe_main().unwrap();
}

fn safe_main() -> Result<(), Error> {
    let arguments = env::args().collect::<Vec<_>>();
    if arguments.len() != 2 {
        eprintln!("Usage: {} SERVER-ADDRESS", arguments[0]);
        process::exit(1);
    }

    let mut server = TcpStream::connect(&arguments[1])?;

    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let command = line?;
        write_command(&mut server, command.as_bytes())?;
        loop {
            let mut buffer = SmallVec::<[u8; 256]>::new();
            let status = read_response_part(&mut server, &mut buffer)?;
            println!("{:?} {}", status, str::from_utf8(&buffer).unwrap());
            if status == ResponsePartStatus::Finish {
                break;
            }
        }
    }

    Ok(())
}
