summaryrefslogtreecommitdiff
path: root/src/modules/refinery.rs
blob: 0e5e1250bf5286b41e1316760c27a47545a9fbdd (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use std::time::SystemTime;

use crate::constants;
use crate::item::{Item, ItemType};
use crate::storage::Storage;

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Refinery {
    time: u64,
    start: Option<SystemTime>,
    pub status: Status,
}

impl Refinery {
    pub fn new() -> Refinery {
        Refinery {
            time: constants::SHIP_REFINERY_TIME,
            start: None,
            status: Status::None,
        }
    }

    pub fn process(&mut self, storage: &mut Storage) {
        if !self.has_crude_minerals(storage) {
            self.off();
        }
        if let Some(timer) = self.start {
            if timer.elapsed().unwrap().as_secs() > self.time {
                self.status = Status::Refined;
                self.start = None
            }
        }
        if self.status == Status::Refined {
            storage.take_item(ItemType::CrudeMinerals);
            storage.give_item(Item::new(ItemType::Iron));
            storage.give_item(Item::new(ItemType::Hydrogen));
            self.taken();
        }
    }

    pub fn get_client_data(&self, storage: &Storage) -> String {
        let client_data = ClientData {
            has_crude_minerals: self.has_crude_minerals(storage),
            status: self.status.clone(),
        };

        serde_json::to_string(&client_data).unwrap() + "\n"
    }

    pub fn give_received_data(&mut self, recv: String) {
        if let "R" = recv.as_str() {
            self.toggle();
        }
    }

    fn has_crude_minerals(&self, storage: &Storage) -> bool {
        storage
            .items
            .iter()
            .any(|item| item.item_type == ItemType::CrudeMinerals)
    }

    fn toggle(&mut self) {
        match self.status {
            Status::None => self.on(),
            _ => self.off(),
        };
    }

    fn on(&mut self) {
        self.start = Some(SystemTime::now());
        self.status = Status::Refining;
    }

    fn off(&mut self) {
        self.start = None;
        self.status = Status::None;
    }

    fn taken(&mut self) {
        self.status = Status::Refining;
        self.start = Some(SystemTime::now());
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClientData {
    pub has_crude_minerals: bool,
    pub status: Status,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum Status {
    None,
    Refining,
    Refined,
}

impl Default for Status {
    fn default() -> Self {
        Status::None
    }
}