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 */
15import telephonySim from '@ohos.telephony.sim';
16import { HiLog } from '../../../../../../common';
17import radio from '@ohos.telephony.radio';
18import observer from '@ohos.telephony.observer';
19
20const TAG = 'SimOpName'
21
22class SimOpName {
23  spnList: Array<string | Resource> = [];
24
25  constructor() {
26    for (let index = 0; index < telephonySim.getMaxSimCount(); index++) {
27      this.spnList[index] = '';
28    }
29  }
30
31  /**
32   * recycle
33   */
34  public unsubscribeSpnObserver() {
35      observer.off('networkStateChange');
36  }
37
38  public initSpnObserver() {
39    try {
40      for (let index = 0; index < telephonySim.getMaxSimCount(); index++) {
41        observer.on('networkStateChange', { slotId: index }, data => {
42          if (!data) {
43            HiLog.e(TAG, 'there is something wrong with networkState');
44            return
45          } else {
46            HiLog.i(TAG, 'observer ON data : ' + JSON.stringify(data));
47            let spn = data.longOperatorName ? data.longOperatorName : data.plmnNumeric;
48            if (spn) {
49              HiLog.i(TAG, `networkStateChange notify Sim${index} Name:${spn}`);
50              this.notifySimName(index, spn);
51            }
52          }
53        });
54      }
55    } catch (err) {
56      HiLog.e(TAG, 'get error: ' + JSON.stringify(err));
57    }
58  }
59
60  public initSimName(simId: number) {
61    radio.getNetworkState(simId, (error, data) => {
62      if (error || !data) {
63        HiLog.e(TAG, 'getNetworkState error: ' + JSON.stringify(error));
64      } else {
65        this.notifySimName(simId, data.longOperatorName);
66      }
67    })
68  }
69
70  public notifySimName(slot: number, spn: string) {
71    HiLog.i(TAG, `notify Sim${slot} Name:${spn}`);
72    this.spnList[slot] = spn;
73    AppStorage.SetOrCreate<Array<string | Resource>>('spnList', this.spnList);
74  }
75}
76
77export default new SimOpName();