1/*
2 * Copyright (c) 2023-2023 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
16import type worker from '@ohos.worker';
17import { Log } from '@ohos/common';
18import CheckEmptyUtils from '@ohos/common';
19import type { WorkerRequest } from '../model/WorkerData';
20import { RequestCode } from '../model/WorkerData';
21
22const TAG = 'WorkerUtil';
23
24export class WorkerUtil {
25
26  public static readonly sCodeToStringMap: Map<RequestCode, string> = new Map([
27    [RequestCode.P2P_START_DISCOVERY, 'start p2p discovery'],
28    [RequestCode.P2P_CANCEL_DISCOVERY, 'cancel p2p discovery'],
29    [RequestCode.GET_CAPS, 'get caps'],
30  ]);
31
32  /**
33   * send request to print worker
34   *
35   * @param printWorker: worker object
36   * @param request: request
37   */
38  public static postMessageToWorkerThread(worker: worker.ThreadWorker, request: WorkerRequest): void {
39    if (CheckEmptyUtils.isEmpty(worker)) {
40      Log.error(TAG, 'worker is undefined');
41      return;
42    }
43    try {
44      worker.postMessage(request);
45    } catch (error) {
46      Log.error(TAG, 'postMessageToWorkerThread error : ' + error);
47    }
48  }
49
50  public static getStringByWorkerCode(code: RequestCode): string {
51    if (code === undefined ) {
52      return '';
53    }
54    return WorkerUtil.sCodeToStringMap.get(code);
55  }
56}