/*
 * Copyright 2025 KylinSoft Co., Ltd.
 *
 * 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 3 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 <https://www.gnu.org/licenses/>.
 */
#include "inputmethodconfigtool.h"

#include <QApplication>

InputMethodConfigTool::InputMethodConfigTool(QWidget *parent)
    : QWidget(parent)
{
  init();
  connectSignals();
}

void InputMethodConfigTool::init()
{
  m_dbus = new FcitxDbusProvider(this);
  m_imModel.reset(new InputMethodListModel(m_dbus, this));
  m_searchDataModel.reset(new SearchDataModel(this));
  m_searchImModel.reset(new SearchInputMethodModel(m_dbus, this));
  m_configManager.reset(new ConfigManager(m_dbus, this));
  m_menuManager.reset(new MenuManager(this));
  m_layout.reset(new LayoutManager(m_dbus, this));

  m_view.reset(new InputMethodConfigToolView(
      m_imModel.get(), m_menuManager.get(), m_configManager.get(),
      m_layout.get(), m_searchDataModel.get(), m_searchImModel.get(),
      [this]()
      { return caculateWindowGeometry(); }));
}

void InputMethodConfigTool::connectSignals()
{
  QObject::connect(m_imModel.get(),
                   &InputMethodListModel::availableInputMethodsChanged,
                   m_searchDataModel.get(),
                   &SearchDataModel::onAvailableInputMethodsChanged);
}

void InputMethodConfigTool::showWindow()
{
  if (m_view == nullptr)
  {
    return;
  }

  makeParentWindowModality();

  m_view->showView();
}

const QPoint InputMethodConfigTool::caculateWindowGeometry() const
{
  return QPoint(500, 300);
}

void InputMethodConfigTool::makeParentWindowModality()
{
  QList<QWindow *> windowList = QApplication::topLevelWindows();
  for (auto *window : windowList)
  {
    if (window->title() == "设置")
    {
      m_view->setModality(Qt::WindowModal);
      m_view->setTransientParent(window);
      break;
    }
  }
}

const QString &InputMethodConfigTool::currentInputMethodName()
{
  return tr("pinyin && sogou input method");
}
