summaryrefslogtreecommitdiff
path: root/src/server/construction.rs
blob: 94a6b0f4fddb1be907a37b9ca691a2871227f4c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
extern crate serde_json;

use std::io::BufRead;
use std::io::Write;
use std::collections::HashMap;

use mass::{Mass, MassType};
use modules::construction::Construction;
use server::connection::ServerConnection;
use modules::construction::ConstructionStatus;
use modules::types::ModuleType;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ConstructionData {
    pub status      : ConstructionStatus,
    pub has_refined : bool,
}

impl ServerConnection {
    pub fn server_construction(&mut self, masses : &mut HashMap<String, Mass>) {
        let mut ship = masses.remove(&self.name).unwrap();
        let ship_clone = ship.clone();

        if let MassType::Ship{ref mut construction, ..} = ship.mass_type {
            let mut construction = construction.as_mut().unwrap();
            let construction_data = get_construction_data(ship_clone.clone(), construction);

            if self.open {
                if self.txrx_construction(&construction_data) {
                    construction.toggle();
                }
            }

            if construction_data.status == ConstructionStatus::Constructed {
                println!("inserted");
                construction.take();
                masses.insert("Station".to_string(), Mass::new_station(ModuleType::Refinery, ship_clone.position, ship_clone.velocity));
            }
        }

        masses.insert(self.name.clone(), ship);
    }

    fn txrx_construction(&mut self, construction_data : &ConstructionData) -> bool {
        let send = serde_json::to_string(construction_data).unwrap() + "\n";
        if let Err(_err) = self.stream.write(send.as_bytes()) {
            self.open = false;
        }

        let mut recv = String::new();
        if let Ok(result) = self.buff_r.read_line(&mut recv) {
            match recv.as_bytes() {
                b"c\n" => {
                    if construction_data.has_refined {
                        return true
                    }
                },
                _ => {
                    if result == 0 {
                        self.open = false;
                    }
                },
            }
        }

        false
    }
}

fn get_construction_data(ship : Mass, construction : &Construction) -> ConstructionData {
    let mut has_refined = false;
    if ship.refined_count() >= 5 {
        has_refined = true;
    }

    ConstructionData {
        status      : construction.status.clone(),
        has_refined : has_refined,
    }
}