/* extension.js
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */
import Gio from 'gi://Gio'
import GObject from 'gi://GObject';

import { Extension } from 'resource:///org/gnome/shell/extensions/extension.js';
import { WebSearcherSearchProvider } from './webSearcherSearchProvider.js';

import * as Main from 'resource:///org/gnome/shell/ui/main.js';
export * as Util from 'resource:///org/gnome/shell/misc/util.js';

const SEARCH_PROVIDERS_SCHEMA = 'org.gnome.desktop.search-providers';

export default class SnapdSearchProviderExtension extends Extension {
  async enable() {
    const cancellable = new Gio.Cancellable();
    this._cancellable = cancellable;

    try {
      const defaultBrowser = await WebSearcherSearchProvider.getDefaultBrowser(cancellable);

      // Ignore if default browser is Web as it already provides a search provider...
      if (!defaultBrowser || defaultBrowser.get_id() === 'org.gnome.Epiphany.desktop') {
        log('No default browser found or default browser is Web, skipping web search provider');
        delete this._cancellable;
        return;
      }

      this.webSearcher = new WebSearcherSearchProvider(defaultBrowser, cancellable);
      this.searchController?.addProvider(this.webSearcher);
      this._monitorSearchSettings();
    } catch (error) {
      if (error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
        return;

      logError(error, 'Error while enabling web search provider');
    }
  }

  disable() {
    this._cancellable?.cancel();
    delete this._cancellable;

    if (this.webSearcher) {
      this._searchSettings.disconnectObject(this);
      delete this._searchSettings;
      this.searchController?.removeProvider(this.webSearcher);
      this.webSearcher?.destroy();
      delete this.webSearcher;
    }
  }

  get searchController() {
    if (!Main.sessionMode.hasOverview)
      return null;

    return Main.overview?.searchController ?? null;
  }

  _monitorSearchSettings() {
    const settings = this.searchController._searchResults?._searchSettings ??
      new Gio.Settings({ schema_id: SEARCH_PROVIDERS_SCHEMA });
    this._searchSettings = settings;

    const reloadSettingsSignals = [
      'changed::disabled',
      'changed::enabled',
      'changed::disable-external',
      'changed::sort-order',
    ];
    const connectArgs = reloadSettingsSignals.flatMap(signal =>
      [signal, () => this._ensureProviderRegistered(), GObject.ConnectFlags.AFTER]);
    settings.connectObject(...connectArgs, this);
  }

  _ensureProviderRegistered() {
    const { searchController } = this;
    const searchResults = searchController?._searchResults;
    if (!searchResults)
      return;

    if (searchResults._providers.includes(this.webSearcher))
      return;

    this.searchController?.addProvider(this.webSearcher);
  }
}
