1/*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import {assertDefined} from 'common/assert_utils';
18import {Timestamp} from 'common/time';
19import {TimeDuration} from 'common/time_duration';
20import {TIMESTAMP_NODE_FORMATTER} from 'trace/tree_node/formatters';
21import {AddOperation} from 'trace/tree_node/operations/add_operation';
22import {PropertyTreeNode} from 'trace/tree_node/property_tree_node';
23import {DEFAULT_PROPERTY_TREE_NODE_FACTORY} from 'trace/tree_node/property_tree_node_factory';
24
25export class AddDuration extends AddOperation<PropertyTreeNode> {
26  protected override makeProperties(
27    value: PropertyTreeNode,
28  ): PropertyTreeNode[] {
29    const wmDataNode = assertDefined(value.getChildByName('wmData'));
30
31    const sendTime: Timestamp | null | undefined = wmDataNode
32      .getChildByName('sendTimeNs')
33      ?.getValue();
34    const finishTime: Timestamp | null | undefined = wmDataNode
35      .getChildByName('finishTimeNs')
36      ?.getValue();
37
38    if (!sendTime || !finishTime) {
39      return [];
40    }
41
42    const timeDiffNs = finishTime.minus(sendTime.getValueNs()).getValueNs();
43    const timeDiff = new TimeDuration(timeDiffNs);
44
45    const durationNode =
46      DEFAULT_PROPERTY_TREE_NODE_FACTORY.makeCalculatedProperty(
47        value.id,
48        'duration',
49        timeDiff,
50      );
51    durationNode.setFormatter(TIMESTAMP_NODE_FORMATTER);
52
53    return [durationNode];
54  }
55}
56