1"""
2  Copyright (c) 2024, The OpenThread Authors.
3  All rights reserved.
4
5  Redistribution and use in source and binary forms, with or without
6  modification, are permitted provided that the following conditions are met:
7  1. Redistributions of source code must retain the above copyright
8     notice, this list of conditions and the following disclaimer.
9  2. Redistributions in binary form must reproduce the above copyright
10     notice, this list of conditions and the following disclaimer in the
11     documentation and/or other materials provided with the distribution.
12  3. Neither the name of the copyright holder nor the
13     names of its contributors may be used to endorse or promote products
14     derived from this software without specific prior written permission.
15
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  POSSIBILITY OF SUCH DAMAGE.
27"""
28import readline
29import shlex
30from argparse import ArgumentParser
31from ble.ble_stream_secure import BleStreamSecure
32from cli.base_commands import (HelpCommand, HelloCommand, CommissionCommand, DecommissionCommand, GetDeviceIdCommand,
33                               GetExtPanIDCommand, GetNetworkNameCommand, GetProvisioningUrlCommand, PingCommand,
34                               ThreadStateCommand, ScanCommand)
35from cli.dataset_commands import (DatasetCommand)
36from dataset.dataset import ThreadDataset
37from typing import Optional
38
39
40class CLI:
41
42    def __init__(self,
43                 dataset: ThreadDataset,
44                 cmd_args: Optional[ArgumentParser] = None,
45                 ble_sstream: Optional[BleStreamSecure] = None):
46        self._commands = {
47            'help': HelpCommand(),
48            'hello': HelloCommand(),
49            'commission': CommissionCommand(),
50            'decommission': DecommissionCommand(),
51            'device_id': GetDeviceIdCommand(),
52            'ext_panid': GetExtPanIDCommand(),
53            'provisioning_url': GetProvisioningUrlCommand(),
54            'network_name': GetNetworkNameCommand(),
55            'ping': PingCommand(),
56            'dataset': DatasetCommand(),
57            'thread': ThreadStateCommand(),
58            'scan': ScanCommand(),
59        }
60        self._context = {
61            'ble_sstream': ble_sstream,
62            'dataset': dataset,
63            'commands': self._commands,
64            'cmd_args': cmd_args
65        }
66        readline.set_completer(self.completer)
67        readline.parse_and_bind('tab: complete')
68
69    def completer(self, text, state):
70        command_pool = self._commands.keys()
71        full_line = readline.get_line_buffer().lstrip()
72        words = full_line.split()
73
74        should_suggest_subcommands = len(words) > 1 or (len(words) == 1 and full_line[-1].isspace())
75        if should_suggest_subcommands:
76            if words[0] not in self._commands.keys():
77                return None
78
79            current_command = self._commands[words[0]]
80            if full_line[-1].isspace():
81                subcommands = words[1:]
82            else:
83                subcommands = words[1:-1]
84            for nextarg in subcommands:
85                if nextarg in current_command._subcommands.keys():
86                    current_command = current_command._subcommands[nextarg]
87                else:
88                    return None
89
90            if len(current_command._subcommands) == 0:
91                return None
92
93            command_pool = current_command._subcommands.keys()
94
95        options = [c for c in command_pool if c.startswith(text)]
96        if state < len(options):
97            return options[state]
98        else:
99            return None
100
101    async def evaluate_input(self, user_input):
102        # do not parse empty commands
103        if not user_input.strip():
104            return
105
106        command_parts = shlex.split(user_input)
107        command = command_parts[0]
108        args = command_parts[1:]
109
110        if command not in self._commands.keys():
111            raise Exception('Invalid command: {}'.format(command))
112
113        return await self._commands[command].execute(args, self._context)
114