summaryrefslogtreecommitdiff
path: root/src/server/navigation.rs
blob: 58d88e75fbc1388da1d35187c666751db671884a (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
extern crate serde_json;

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

use math::distance;
use module::{ModuleType, NavigationStatus};
use mass::{Mass, MassType};
use connection::Connection;

impl Connection {
    pub fn server_navigation(&mut self, masses : &mut HashMap<String, Mass>) -> bool {
        let masses_clone = masses.clone();
        let ship = masses.get_mut(&self.name).unwrap();
        let ship_position = ship.position;

        match ship.mass_type {
            MassType::Ship{ref mut modules, ..} => {
                match modules.get_mut("Navigation").unwrap().module_type {
                    ModuleType::Navigation{ref mut target_name, ref mut start, ref mut status, ref range, ..} => {
                        match target_name.clone() {
                            Some(name) => {
                                let target = masses_clone.get(&name).unwrap();
                                if distance(target.position, ship.position) > *range {
                                    *target_name = None;
                                }
                            },
                            _ => (),
                        }

                        let within_range : HashMap<&String, &Mass> = masses_clone.iter().filter(|&(_, mass)|
                                                                                                distance(ship_position, mass.position) < *range)
                                                                                                .collect();

                        let send = serde_json::to_string(&within_range).unwrap() + "\n";
                        match self.stream.write(send.as_bytes()) {
                            Ok(_result) => (),
                            Err(_error) => return false,
                        }

                        let mut recv = String::new();
                        match self.buff_r.read_line(&mut recv) {
                            Ok(_result) => (),
                            Err(_error) => (),
                        }
                        if !recv.is_empty() {
                            *target_name = Some(recv.replace("\n", ""));
                            *start = Some(SystemTime::now());
                            *status = NavigationStatus::Targeting;
                        }
                    },
                _ => (),
                }
            }
        _ => (),
        }
        true
    }
}