1"""
2   Copyright (c) 2023 Nordic Semiconductor ASA
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15"""
16
17from typing import Dict, List
18
19from tlv.tlv import TLV
20from tlv.dataset_tlv import MeshcopTlvType
21from dataset.dataset_entries import DatasetEntry, create_dataset_entry
22
23initial_dataset = bytes([
24    0x0E, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x12, 0x35, 0x06, 0x00, 0x04,
25    0x00, 0x1F, 0xFF, 0xE0, 0x02, 0x08, 0xEF, 0x13, 0x98, 0xC2, 0xFD, 0x50, 0x4B, 0x67, 0x07, 0x08, 0xFD, 0x35, 0x34,
26    0x41, 0x33, 0xD1, 0xD7, 0x3E, 0x05, 0x10, 0xFD, 0xA7, 0xC7, 0x71, 0xA2, 0x72, 0x02, 0xE2, 0x32, 0xEC, 0xD0, 0x4C,
27    0xF9, 0x34, 0xF4, 0x76, 0x03, 0x0F, 0x4F, 0x70, 0x65, 0x6E, 0x54, 0x68, 0x72, 0x65, 0x61, 0x64, 0x2D, 0x63, 0x36,
28    0x34, 0x65, 0x01, 0x02, 0xC6, 0x4E, 0x04, 0x10, 0x5E, 0x9B, 0x9B, 0x36, 0x0F, 0x80, 0xB8, 0x8B, 0xE2, 0x60, 0x3F,
29    0xB0, 0x13, 0x5C, 0x8D, 0x65, 0x0C, 0x04, 0x02, 0xA0, 0xF7, 0xF8
30])
31
32
33class ThreadDataset:
34
35    def __init__(self):
36        self.entries: Dict[MeshcopTlvType, DatasetEntry] = {}
37        self.set_from_bytes(initial_dataset)
38
39    def print_content(self):
40        for type, entry in self.entries.items():
41            print(f'{type.name}:')
42            entry.print_content(indent=1)
43            print()
44
45    def set_from_bytes(self, bytes):
46        for tlv in TLV.parse_tlvs(bytes):
47            type = MeshcopTlvType.from_value(tlv.type)
48            self.entries[type] = create_dataset_entry(type)
49            self.entries[type].set_from_tlv(tlv)
50
51    def to_bytes(self):
52        res = bytes()
53        for entry in self.entries.values():
54            res += entry.to_tlv().to_bytes()
55        return res
56
57    def get_entry(self, type: MeshcopTlvType):
58        return self.entries[type]
59
60    def set_entry(self, type: MeshcopTlvType, args: List[str]):
61        if type in self.entries:
62            self.entries[type].set(args)
63            return
64        raise KeyError(f'Key {type} not available in the dataset.')
65