1/*
2 * Copyright (c) 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 { Log } from '../utils/Log'
17import type { IModeMap } from './IModeMap'
18import type { FunctionId } from './FunctionId'
19
20export class ModeAssembler {
21  private TAG: string = '[ModeAssembler]:'
22  private mNeedAdd: FunctionId[]
23  private mNeedDelete: FunctionId[]
24  private mMode: IModeMap
25  private mFunctionsMap: Map<FunctionId, any>
26
27  constructor(functionsMap: Map<FunctionId, any>, modeMap: IModeMap) {
28    this.mFunctionsMap = functionsMap
29    this.mMode = modeMap
30  }
31
32  public assembler(preMode: string, currentMode: string): void {
33    Log.info(`${this.TAG} assembler preMode = ${preMode}  currentMode = ${currentMode} E `)
34    this.mNeedAdd = []
35    this.mNeedDelete = []
36    Log.info(`${this.TAG} assembler preMode = ${this.mMode.getFunctions(preMode)}  currentMode = ${this.mMode.getFunctions(currentMode)} E `)
37
38    let preModeFun: FunctionId[] = this.mMode.getFunctions(preMode)
39    let currentModeFun: FunctionId[] = this.mMode.getFunctions(currentMode)
40
41    Log.info(`${this.TAG} assembler preModeFun = ${preModeFun}  currentModeFun = ${currentModeFun}  `)
42    if (!preMode) {
43      this.mNeedAdd = JSON.parse(JSON.stringify(currentModeFun))
44    } else if (preMode != currentMode) {
45      this.mNeedAdd = JSON.parse(JSON.stringify(currentModeFun))
46      for (let fun of preModeFun) {
47        let index = currentModeFun.indexOf(fun)
48          if (index == -1) {
49            this.mNeedDelete.push(fun)
50          } else {
51            this.mNeedAdd.splice(index, 1)
52          }
53      }
54    }
55    Log.info(`${this.TAG} assembler mNeedAdd = ${this.mNeedAdd}  mNeedDelete = ${this.mNeedDelete}`)
56    this.attachFunction(this.mNeedAdd)
57    this.detachFunction(this.mNeedDelete)
58    Log.info(`${this.TAG} assembler X`)
59  }
60
61  private attachFunction(item: FunctionId[]): void {
62    for (let fun of item) {
63      Log.info(`${this.TAG} attachFunction fun: ${fun}`)
64      this.mFunctionsMap.get(fun).load()
65    }
66  }
67
68  private detachFunction(item: FunctionId[]): void {
69    for (let fun of item) {
70      Log.info(`${this.TAG} disattachFunction fun: ${fun}`)
71      this.mFunctionsMap.get(fun).unload()
72    }
73  }
74}