use client::{self, Client};
use futures::Future;
use futures::future::{self, FutureResult, Loop};
use std::io;
use tokio_service::Service;
use twist::WebSocketFrame;
pub struct LineReader {
client: Client,
current_line: String,
}
impl LineReader {
pub fn new(client: Client) -> LineReader {
LineReader {
client: client,
current_line: String::new(),
}
}
pub fn current_line(&self) -> String {
self.current_line.clone()
}
pub fn read_line(mut self) -> FutureResult<LineReader, io::Error> {
let mut buf = String::new();
match io::stdin().read_line(&mut buf) {
Ok(_) => {
self.current_line = buf;
if self.current_line.starts_with("exit") {
future::err(client::other("exiting"))
} else {
future::done(Ok(self))
}
}
Err(e) => future::err(e),
}
}
pub fn call(self, frame: WebSocketFrame) -> Box<Future<Item = Loop<LineReader, LineReader>, Error = io::Error>> {
Box::new(self.client.call(frame)
.and_then(|resp| -> Result<Loop<LineReader, LineReader>, io::Error> {
Ok(Loop::Continue(self))
})
.or_else(|e| -> Result<Loop<LineReader, LineReader>, io::Error> {
println!("error: {}", e);
Err(e)
}))
}
}