// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import '../../ui/legacy/legacy.js';

import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as ObjectUI from '../../ui/legacy/components/object_ui/object_ui.js';
import * as UI from '../../ui/legacy/legacy.js';
import {Directives, html, nothing, render} from '../../ui/lit/lit.js';
import * as VisualLogging from '../../ui/visual_logging/visual_logging.js';

import propertiesWidgetStyles from './propertiesWidget.css.js';

const OBJECT_GROUP_NAME = 'properties-sidebar-pane';

const {bindToSetting} = UI.UIUtils;
const {repeat} = Directives;

const UIStrings = {
  /**
   * @description Text on the checkbox in the Properties tab of the Elements panel, which controls whether
   * all properties of the currently selected DOM element are shown, or only meaningful properties (i.e.
   * excluding properties whose values aren't set for example).
   */
  showAll: 'Show all',
  /**
   * @description Tooltip on the checkbox in the Properties tab of the Elements panel, which controls whether
   * all properties of the currently selected DOM element are shown, or only meaningful properties (i.e.
   * excluding properties whose values aren't set for example).
   */
  showAllTooltip: 'When unchecked, only properties whose values are neither null nor undefined will be shown',
  /**
   * @description Text shown to the user when a filter is applied in the Properties tab of the Elements panel, but
   * no properties matched the filter and thus no results were returned.
   */
  noMatchingProperty: 'No matching property',
} as const;
const str_ = i18n.i18n.registerUIStrings('panels/elements/PropertiesWidget.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);

interface PropertiesWidgetInput {
  onFilterChanged: (e: CustomEvent<string>) => void;
  onRegexToggled: () => void;
  isRegex: boolean;
  objectTree: ObjectUI.ObjectPropertiesSection.ObjectTree|null;
  allChildrenFiltered: boolean;
}

type View = (input: PropertiesWidgetInput, output: object, target: HTMLElement) => void;

export const DEFAULT_VIEW: View = (input, _output, target) => {
  // clang-format off
  render(html`
    <div jslog=${VisualLogging.pane('element-properties').track({resize: true})}>
      <div class="hbox properties-widget-toolbar">
        <devtools-toolbar class="styles-pane-toolbar" role="presentation">
          <devtools-toolbar-input
            type="filter"
            ?regex=${true}
            @change=${input.onFilterChanged}
            @regextoggle=${input.onRegexToggled}
            style="flex-grow:1; flex-shrink:1"
          ></devtools-toolbar-input>
          <devtools-checkbox title=${i18nString(UIStrings.showAllTooltip)} ${bindToSetting(getShowAllPropertiesSetting())}>
            ${i18nString(UIStrings.showAll)}
          </devtools-checkbox>
        </devtools-toolbar>
      </div>
      ${input.objectTree && input.allChildrenFiltered ? html`
        <div class="gray-info-message">${i18nString(UIStrings.noMatchingProperty)}</div>
      ` : nothing}
      <devtools-tree .template=${html`
        <ul role=tree class="source-code object-properties-section">
          <style>${ObjectUI.ObjectPropertiesSection.objectValueStyles}</style>;
          <style>${ObjectUI.ObjectPropertiesSection.objectPropertiesSectionStyles}</style>;
          ${repeat(ObjectUI.ObjectPropertiesSection.ObjectPropertyTreeElement.createPropertyNodes(
                        input.objectTree?.children ?? {},
                        true /* skipProto */,
                        true /* skipGettersAndSetters */),
                   node => html`<devtools-tree-wrapper .treeElement=${node}></devtools-tree-wrapper>`)}
        </ul>
      `}></devtools-tree>
    </div>`, target);
  // clang-format on
};

const getShowAllPropertiesSetting = (): Common.Settings.Setting<boolean> =>
    Common.Settings.Settings.instance().createSetting('show-all-properties', /* defaultValue */ false);

export class PropertiesWidget extends UI.Widget.VBox {
  private readonly showAllPropertiesSetting: Common.Settings.Setting<boolean>;
  private filterRegex: RegExp|null = null;
  private readonly treeOutline: ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeOutline;
  #lastRequestedNode: SDK.DOMModel.DOMNode|null = null;
  readonly #view: View;
  #pendingNodeUpdate = true;
  #objectTree: ObjectUI.ObjectPropertiesSection.ObjectTree|null = null;
  #isRegex = false;
  #filterText = '';

  constructor(view: View = DEFAULT_VIEW) {
    super({useShadowDom: true});
    this.registerRequiredCSS(propertiesWidgetStyles);

    this.showAllPropertiesSetting = getShowAllPropertiesSetting();
    this.showAllPropertiesSetting.addChangeListener(this.onFilterChanged.bind(this));

    SDK.TargetManager.TargetManager.instance().addModelListener(
        SDK.DOMModel.DOMModel, SDK.DOMModel.Events.AttrModified, this.onNodeChange, this, {scoped: true});
    SDK.TargetManager.TargetManager.instance().addModelListener(
        SDK.DOMModel.DOMModel, SDK.DOMModel.Events.AttrRemoved, this.onNodeChange, this, {scoped: true});
    SDK.TargetManager.TargetManager.instance().addModelListener(
        SDK.DOMModel.DOMModel, SDK.DOMModel.Events.CharacterDataModified, this.onNodeChange, this, {scoped: true});
    SDK.TargetManager.TargetManager.instance().addModelListener(
        SDK.DOMModel.DOMModel, SDK.DOMModel.Events.ChildNodeCountUpdated, this.onNodeChange, this, {scoped: true});
    UI.Context.Context.instance().addFlavorChangeListener(SDK.DOMModel.DOMNode, this.setNode, this);

    this.#view = view;
    this.treeOutline = new ObjectUI.ObjectPropertiesSection.ObjectPropertiesSectionsTreeOutline();
    this.treeOutline.setShowSelectionOnKeyboardFocus(/* show */ true, /* preventTabOrder */ false);

    this.treeOutline.addEventListener(UI.TreeOutline.Events.ElementExpanded, () => {
      Host.userMetrics.actionTaken(Host.UserMetrics.Action.DOMPropertiesExpanded);
    });

    this.requestUpdate();
  }

  #buildFilterRegex(text: string): RegExp|null {
    if (!text) {
      return null;
    }
    if (this.#isRegex) {
      try {
        return new RegExp(text, 'i');
      } catch {
        // Invalid regex: fall through to plain-text matching.
      }
    }
    return new RegExp(Platform.StringUtilities.escapeForRegExp(text), 'i');
  }

  private onFilterChanged(event: CustomEvent<string>|Common.EventTarget.EventTargetEvent<boolean>): void {
    if ('detail' in event) {
      this.#filterText = event.detail;
      this.filterRegex = this.#buildFilterRegex(event.detail);
    }
    this.#updateFilter();
    this.requestUpdate();
  }

  private onRegexToggled(): void {
    this.#isRegex = !this.#isRegex;
    this.filterRegex = this.#buildFilterRegex(this.#filterText);
    this.#updateFilter();
    this.requestUpdate();
  }

  #updateFilter(): void {
    this.#objectTree?.setFilter({
      includeNullOrUndefinedValues: this.showAllPropertiesSetting.get(),
      regex: this.filterRegex,
    });
  }

  private setNode(): void {
    this.#pendingNodeUpdate = true;
    this.requestUpdate();
  }

  async #updateNodeIfRequired(): Promise<void> {
    if (!this.#pendingNodeUpdate) {
      return;
    }
    this.#pendingNodeUpdate = false;
    this.#lastRequestedNode?.domModel().runtimeModel().releaseObjectGroup(OBJECT_GROUP_NAME);
    this.#lastRequestedNode = UI.Context.Context.instance().flavor(SDK.DOMModel.DOMNode);

    if (!this.#lastRequestedNode) {
      this.#objectTree = null;
      return;
    }
    const object = await this.#lastRequestedNode.resolveToObject(OBJECT_GROUP_NAME);
    if (!object) {
      return;
    }

    this.#objectTree = new ObjectUI.ObjectPropertiesSection.ObjectTree(object, {
      propertiesMode: ObjectUI.ObjectPropertiesSection.ObjectPropertiesMode.OWN_AND_INTERNAL_AND_INHERITED,
      readOnly: true,
    });
    this.#updateFilter();
  }

  override async performUpdate(): Promise<void> {
    await this.#updateNodeIfRequired();
    await this.#objectTree?.populateChildrenIfNeeded();
    const allChildrenFiltered =
        !(this.#objectTree?.children?.accessors?.some(c => !c.isFiltered) ||
          this.#objectTree?.children?.arrayRanges?.some(() => true) ||
          this.#objectTree?.children?.internalProperties?.some(c => !c.isFiltered) ||
          this.#objectTree?.children?.properties?.some(c => !c.isFiltered));
    this.#view(
        {
          onFilterChanged: this.onFilterChanged.bind(this),
          onRegexToggled: this.onRegexToggled.bind(this),
          isRegex: this.#isRegex,
          allChildrenFiltered,
          objectTree: this.#objectTree,
        },
        {}, this.contentElement);
  }

  private onNodeChange(
      event: Common.EventTarget.EventTargetEvent<{node: SDK.DOMModel.DOMNode, name: string}|SDK.DOMModel.DOMNode>,
      ): void {
    if (!this.#lastRequestedNode) {
      return;
    }
    const data = event.data;
    const node = (data instanceof SDK.DOMModel.DOMNode ? data : data.node);
    if (this.#lastRequestedNode !== node) {
      return;
    }
    this.#pendingNodeUpdate = true;
    this.requestUpdate();
  }
}
