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
16import Log from "../Log";
17
18export type EventTarget = "local" | "remote" | "ability" | "commonEvent";
19export type Event = {
20    target: EventTarget;
21    data: { [key: string]: any };
22};
23export type EventParser = {
24    [key in EventTarget]: (data: any) => boolean;
25};
26export type LocalEvent = {
27    eventName: string;
28    args: any;
29};
30
31export const START_ABILITY_EVENT = "startAbilityEvent";
32export const PUBLISH_COMMON_EVENT = "publishCommonEvent";
33
34const TAG = "EventUtil";
35const LOCAL_EVENT_TYPE = "local";
36const START_ABILITY_TYPE = "ability";
37
38export function obtainLocalEvent(event: string, args: any): Event & { data: LocalEvent } {
39    return {
40        target: LOCAL_EVENT_TYPE,
41        data: {
42            eventName: event,
43            args,
44        },
45    };
46}
47
48export function obtainStartAbility(bundleName: string, abilityName: string, args?: any): Event {
49    return {
50        target: START_ABILITY_TYPE,
51        data: {
52            bundleName,
53            abilityName,
54            args
55        },
56    };
57}
58
59export function parseEventString(eventString: string | undefined): Event | undefined {
60    // string must be "local=eventName|args" or "ability=bundleName|abilityName"
61    if (!eventString) {
62        return;
63    }
64    let [eventType, eventData] = eventString.split("=");
65    if (eventType == LOCAL_EVENT_TYPE && eventData) {
66        let [localEventName, args] = eventData.split("|");
67        if (localEventName) {
68            Log.showDebug(TAG, `parseEventData name:${localEventName}, args: ${args}`);
69            return obtainLocalEvent(localEventName, args);
70        }
71    }
72    if (eventType == START_ABILITY_TYPE && eventData) {
73        let [bundleName, abilityName] = eventData.split("|");
74        if (bundleName && abilityName) {
75            Log.showDebug(TAG, `parseEventData bundleName:${bundleName}, abilityName: ${abilityName}`);
76            return obtainStartAbility(bundleName, abilityName);
77        }
78    }
79    Log.showError(TAG, `Can't parse event data: ${eventString}`);
80    return undefined;
81}
82