1 /*
2  * Copyright (c) 2022 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 #ifndef OHOS_DISTRIBUTED_ABILITY_MANAGER_JS_DEVICE_SELECTION_LISTENER_H
17 #define OHOS_DISTRIBUTED_ABILITY_MANAGER_JS_DEVICE_SELECTION_LISTENER_H
18 
19 #include <map>
20 #include <mutex>
21 
22 #include "device_selection_notifier_stub.h"
23 #include "native_engine/native_engine.h"
24 
25 namespace OHOS {
26 namespace DistributedSchedule {
27 class JsDeviceSelectionListener : public DeviceSelectionNotifierStub {
28 public:
JsDeviceSelectionListener(napi_env env)29     explicit JsDeviceSelectionListener(napi_env env) : engine_(env) {}
30     virtual ~JsDeviceSelectionListener() = default;
31 
32     void OnDeviceConnect(const std::vector<ContinuationResult>& continuationResults) override;
33     void OnDeviceDisconnect(const std::vector<ContinuationResult>& continuationResults) override;
34 
35     void AddCallback(const std::string& cbType, napi_value jsListenerObj);
36     void RemoveCallback(const std::string& cbType);
37 
38 private:
39     void CallJsMethod(const std::string& methodName, const std::vector<ContinuationResult>& continuationResults);
40     void CallJsMethod(const std::string& methodName, const std::vector<std::string>& deviceIds);
41     void CallJsMethodInner(const std::string& methodName, const std::vector<ContinuationResult>& continuationResults);
42     void CallJsMethodInner(const std::string& methodName, const std::vector<std::string>& deviceIds);
43     napi_value WrapContinuationResult(napi_env env, const ContinuationResult& continuationResult);
44     napi_value WrapContinuationResultArray(napi_env env,
45         const std::vector<ContinuationResult>& continuationResults);
46     napi_value WrapDeviceIdArray(napi_env env, const std::vector<std::string>& deviceIds);
47     void SetKeyValue(napi_env env,
48         const napi_value object, const std::string &strKey, const std::string &strValue) const;
49 
50     napi_env engine_ = nullptr;
51     std::mutex jsCallBackMapMutex_;
52     std::map<std::string, std::unique_ptr<NativeReference>> jsCallBackMap_;
53 };
54 } // namespace DistributedSchedule
55 } // namespace OHOS
56 #endif // OHOS_DISTRIBUTED_ABILITY_MANAGER_JS_DEVICE_SELECTION_LISTENER_H