// License: see LICENSE file at root directory of `master` branch

//! # Response sender

use std::{
    io::{BufWriter, Read, Write},
};

use blackhole::Job;
use native_tls::TlsStream;
use xz2::write::XzEncoder;

/// # Response sender
pub struct ResponseSender<S> where S: Read + Write {
    stream: Option<TlsStream<S>>,
    response: Vec<u8>,
}

impl<S> ResponseSender<S> where S: Read + Write {

    /// # Makes new instance
    pub fn new(stream: TlsStream<S>, response: Vec<u8>) -> Self {
        Self {
            stream: Some(stream),
            response,
        }
    }

}

impl<S> Job for ResponseSender<S> where S: Read + Write + Send + 'static {

    fn run(&mut self) -> Option<Box<dyn Job>> {
        match self.stream.take() {
            Some(stream) => if let Err(err) = XzEncoder::new(BufWriter::new(stream), 6).write_all(&self.response) {
                __e!("Failed sending response: {:?}", err);
            },
            None => print_internal_error!(),
        };

        None
    }

}
