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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use crate::codec::*;
use crate::coreobj::CoreObjectType;
use cyfs_base::*;
use serde::Serialize;

use std::str::FromStr;

#[derive(Debug, Clone, ProtobufEncode, ProtobufDecode, ProtobufTransform, Serialize)]
#[cyfs_protobuf_type(crate::codec::protos::ZoneDescContent)]
pub struct ZoneDescContent {
    // People/SimpleGroup
    // 一个device在没有owner情况下,所在zone的owner就是自己,并且该zone只有自己一台设备
    owner: ObjectId,
}

impl DescContent for ZoneDescContent {
    fn obj_type() -> u16 {
        CoreObjectType::Zone as u16
    }

    fn format(&self) -> u8 {
        OBJECT_CONTENT_CODEC_FORMAT_PROTOBUF
    }

    type OwnerType = Option<ObjectId>;
    type AreaType = SubDescNone;
    type AuthorType = SubDescNone;
    type PublicKeyType = SubDescNone;
}

#[derive(Clone, Debug, ProtobufEncode, ProtobufDecode, ProtobufTransformType, Serialize)]
#[cyfs_protobuf_type(crate::codec::protos::ZoneBodyContent)]
pub struct ZoneBodyContent {
    ood_work_mode: OODWorkMode,
    ood_list: Vec<DeviceId>,
    known_device_list: Vec<DeviceId>,
}

impl BodyContent for ZoneBodyContent {
    fn format(&self) -> u8 {
        OBJECT_CONTENT_CODEC_FORMAT_PROTOBUF
    }
}

impl ProtobufTransform<protos::ZoneBodyContent> for ZoneBodyContent {
    fn transform(value: protos::ZoneBodyContent) -> BuckyResult<Self> {
        let mut ret = Self {
            ood_list: ProtobufCodecHelper::decode_buf_list(value.ood_list)?,
            known_device_list: ProtobufCodecHelper::decode_buf_list(value.known_device_list)?,
            ood_work_mode: OODWorkMode::Standalone,
        };

        if let Some(ood_work_mode) = value.ood_work_mode {
            ret.ood_work_mode = OODWorkMode::from_str(&ood_work_mode)?;
        }

        Ok(ret)
    }
}
impl ProtobufTransform<&ZoneBodyContent> for protos::ZoneBodyContent {
    fn transform(value: &ZoneBodyContent) -> BuckyResult<Self> {
        let ret = Self {
            ood_list: ProtobufCodecHelper::encode_buf_list(&value.ood_list)?.into_vec(),
            known_device_list: ProtobufCodecHelper::encode_buf_list(&value.known_device_list)?
                .into_vec(),
            ood_work_mode: Some(value.ood_work_mode.to_string()),
        };

        Ok(ret)
    }
}

type ZoneType = NamedObjType<ZoneDescContent, ZoneBodyContent>;
type ZoneBuilder = NamedObjectBuilder<ZoneDescContent, ZoneBodyContent>;
type ZoneDesc = NamedObjectDesc<ZoneDescContent>;

pub type ZoneId = NamedObjectId<ZoneType>;
pub type Zone = NamedObjectBase<ZoneType>;

pub trait ZoneObj {
    fn create(
        owner: ObjectId,
        ood_work_mode: OODWorkMode,
        ood_list: Vec<DeviceId>,
        known_device_list: Vec<DeviceId>,
    ) -> Self;
    fn owner(&self) -> &ObjectId;

    fn ood_work_mode(&self) -> &OODWorkMode;
    fn set_ood_work_mode(&mut self, work_mode: OODWorkMode);

    fn ood(&self) -> &DeviceId;
    fn ood_list(&self) -> &Vec<DeviceId>;
    fn ood_list_mut(&mut self) -> &mut Vec<DeviceId>;

    fn ood_index(&self, device_id: &DeviceId) -> BuckyResult<usize>;

    fn known_device_list(&self) -> &Vec<DeviceId>;
    fn known_device_list_mut(&mut self) -> &mut Vec<DeviceId>;

    fn device_index(&self, device_id: &DeviceId) -> BuckyResult<usize>;

    fn zone_id(&self) -> ZoneId;
    fn is_ood(&self, device_id: &DeviceId) -> bool;
    fn is_known_device(&self, device_id: &DeviceId) -> bool;
}

impl ZoneObj for Zone {
    fn create(
        owner: ObjectId,
        ood_work_mode: OODWorkMode,
        ood_list: Vec<DeviceId>,
        known_device_list: Vec<DeviceId>,
    ) -> Self {
        assert!(ood_list.len() > 0);

        let body = ZoneBodyContent {
            ood_work_mode,
            ood_list,
            known_device_list,
        };
        let desc = ZoneDescContent { owner };
        ZoneBuilder::new(desc, body).no_create_time().build()
    }

    fn owner(&self) -> &ObjectId {
        &self.desc().content().owner
    }

    fn ood_work_mode(&self) -> &OODWorkMode {
        &self.body().as_ref().unwrap().content().ood_work_mode
    }

    fn set_ood_work_mode(&mut self, work_mode: OODWorkMode) {
        self.body_mut()
            .as_mut()
            .unwrap()
            .content_mut()
            .ood_work_mode = work_mode;
    }

    fn ood(&self) -> &DeviceId {
        &self.body().as_ref().unwrap().content().ood_list[0]
    }

    fn ood_list(&self) -> &Vec<DeviceId> {
        &self.body().as_ref().unwrap().content().ood_list
    }

    fn ood_list_mut(&mut self) -> &mut Vec<DeviceId> {
        &mut self.body_mut().as_mut().unwrap().content_mut().ood_list
    }

    fn ood_index(&self, device_id: &DeviceId) -> BuckyResult<usize> {
        for (i, id) in self
            .body()
            .as_ref()
            .unwrap()
            .content()
            .ood_list
            .iter()
            .enumerate()
        {
            if id == device_id {
                return Ok(i);
            }
        }

        Err(BuckyError::from(BuckyErrorCode::NotFound))
    }

    fn known_device_list(&self) -> &Vec<DeviceId> {
        &self.body().as_ref().unwrap().content().known_device_list
    }

    fn known_device_list_mut(&mut self) -> &mut Vec<DeviceId> {
        &mut self
            .body_mut()
            .as_mut()
            .unwrap()
            .content_mut()
            .known_device_list
    }

    fn device_index(&self, device_id: &DeviceId) -> BuckyResult<usize> {
        for (i, id) in self
            .body()
            .as_ref()
            .unwrap()
            .content()
            .known_device_list
            .iter()
            .enumerate()
        {
            if id == device_id {
                return Ok(i);
            }
        }

        Err(BuckyError::from(BuckyErrorCode::NotFound))
    }

    fn zone_id(&self) -> ZoneId {
        self.desc().calculate_id().try_into().unwrap()
    }

    fn is_known_device(&self, device_id: &DeviceId) -> bool {
        if self.is_ood(device_id) {
            return true;
        }

        self.body()
            .as_ref()
            .unwrap()
            .content()
            .known_device_list
            .iter()
            .any(|id| id == device_id)
    }

    fn is_ood(&self, device_id: &DeviceId) -> bool {
        self.ood_list().iter().find(|&v| *v == *device_id).is_some()
    }
}

#[cfg(test)]
mod test {
    use crate::*;
    use cyfs_base::*;

    use std::str::FromStr;

    #[test]
    fn test() {
        let owner = ObjectId::from_str("5aSixgLtjoYcAFH9isc6KCqDgKfTJ8jpgASAoiRz5NLk").unwrap();
        let ood = DeviceId::from_str("5aSixgPXvhR4puWzFCHqvUXrjFWjxbq4y3thJVgZg6ty").unwrap();

        let zone = Zone::create(
            owner,
            OODWorkMode::Standalone,
            vec![ood.clone()],
            vec![ood.clone()],
        );
        let buf = zone.to_vec().unwrap();
        let zone2 = Zone::clone_from_slice(&buf).unwrap();

        assert_eq!(zone2.owner(), zone.owner());
        assert_eq!(zone2.ood_list()[0], ood);
        assert_eq!(zone2.known_device_list()[0], ood);

        let path = cyfs_util::get_app_data_dir("tests");
        std::fs::create_dir_all(&path).unwrap();
        let name = path.join("zone.desc");
        std::fs::write(&name, buf).unwrap();
    }
}