1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "shell_command.h"
17
18#include <getopt.h>
19
20#include "edm_log.h"
21
22namespace OHOS {
23namespace EDM {
24ShellCommand::ShellCommand(int argc, char *argv[], std::string name)
25{
26    opterr = 0;
27    argc_ = argc;
28    argv_ = argv;
29    name_ = name;
30
31    if (argc < MIN_ARGUMENT_NUMBER) {
32        cmd_ = "help";
33        return;
34    }
35    cmd_ = argv[1];
36}
37
38ErrCode ShellCommand::OnCommand()
39{
40    if (commandMap_.find("help") == commandMap_.end()) {
41        return ERR_INVALID_VALUE;
42    }
43    auto respond = commandMap_["help"];
44    if (commandMap_.find(cmd_) != commandMap_.end()) {
45        respond = commandMap_[cmd_];
46    }
47    if (Init() != ERR_OK) {
48        return ERR_INVALID_VALUE;
49    }
50    respond();
51    return ERR_OK;
52}
53
54std::string ShellCommand::ExecCommand()
55{
56    ErrCode result = CreateCommandMap();
57    if (result != ERR_OK) {
58        EDMLOGE("failed to create command map.\n");
59    }
60
61    result = CreateMessageMap();
62    if (result != ERR_OK) {
63        EDMLOGE("failed to create message map.\n");
64    }
65
66    result = OnCommand();
67    if (result != ERR_OK) {
68        EDMLOGE("failed to execute your command.\n");
69        resultReceiver_ = "error: failed to execute your command.\n";
70    }
71    return resultReceiver_;
72}
73
74std::string ShellCommand::GetMessageFromCode(int32_t code) const
75{
76    EDMLOGI("ShellCommand::GetMessageFromCode enter.");
77
78    std::string result;
79    if (messageMap_.find(code) != messageMap_.end()) {
80        std::string message = messageMap_.at(code);
81        if (!message.empty()) {
82            result.append(message + "\n");
83        }
84    }
85    return result;
86}
87} // namespace EDM
88} // namespace OHOS
89