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 */
15import { buffer } from '@kit.ArkTS';
16import { HiLog } from './HiLog';
17
18const TAG = 'CommonUtil';
19
20export default class CommonUtil {
21
22  public static readonly DEFAULT_ZERO: number = 0;
23
24  public static readonly UTF_8: buffer.BufferEncoding = 'utf-8';
25  public static readonly BASE64: buffer.BufferEncoding = 'base64';
26
27  public static isEmptyStr(input: string): boolean {
28    return (input == null || input === undefined || input.trim() === '' || input.length === 0);
29  }
30
31  public static isEmptyArray<T>(input: Array<T>): boolean {
32    return (input == null || input === undefined || input.length === 0);
33  }
34
35  public static encodeByBase64(data: string | undefined): string {
36    if (this.isEmptyStr(data)) {
37      return '';
38    }
39    try {
40      return buffer.from(data, CommonUtil.UTF_8).toString(CommonUtil.BASE64);
41    } catch (error) {
42      HiLog.error(TAG, `encodeByBase64 error: ${error}`);
43    }
44    return '';
45  }
46
47  /**
48   * remark: not support concurrent
49   * @param key
50   * @param increaseNum
51   * @returns
52   */
53  public static increaseByAppStorageKey(key: string, increaseNum: number): number {
54    let oldVal = AppStorage.get(key) as number;
55    if (!oldVal) {
56      oldVal = CommonUtil.DEFAULT_ZERO;
57    }
58    if (!increaseNum || isNaN(increaseNum)) {
59      increaseNum = 1;
60    }
61    let newVal = oldVal + increaseNum;
62    AppStorage.setOrCreate(key, newVal);
63    return newVal;
64  }
65
66  /**
67   * delay
68   * @param delay unit is mill sec
69   */
70  public static delay(delay: number): void {
71    let currentTime = new Date().getTime();
72    while (new Date().getTime() < currentTime + delay) {
73      continue;
74    }
75  }
76}