// Rshare - a file sharing program written in Rust.
// Copyright (C) 2017 Cooper Paul EdenDay
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// Electronic mail: cedenday@protonmail.com
// Paper mail: 100 Front Street, #31, Bath, Maine, 04530, USA

pub mod wrapper;
pub mod message;
pub mod itc;

use std;
use std::net::IpAddr;
use std::sync::Arc;
use chashmap::CHashMap;
use std::io::Write;
use std::time::Duration;
use constants::PORT;
use constants::TIMEOUT;

pub fn encode(encode_message: &message::Message) -> Vec<u8> {
    wrapper::encode(&message::encode(encode_message))
}

pub fn send(registered_peers: Arc<CHashMap<IpAddr, ()>>,
            send_message: &message::Message,
            destination: IpAddr) {
    let socket = std::net::SocketAddr::new(destination, PORT);
    let connection = std::net::TcpStream::connect(socket);
    if let Ok(mut connection) = connection {
        registered_peers.insert(destination, ());
        connection
            .set_write_timeout(Some(Duration::from_secs(TIMEOUT)))
            .unwrap();
        let _ = connection.write_all(&encode(send_message));
    } else {
        registered_peers.remove(&destination);
    }
}
