#include "alias-form-view-host.hpp"
#include "navigation-controller.hpp"
#include "service-registry.hpp"
#include "services/root-item-manager/root-item-manager.hpp"
#include "services/toast/toast-service.hpp"
#include "ui/action-pannel/action.hpp"
#include <QUrl>

AliasFormViewHost::AliasFormViewHost(EntrypointId id) : FormViewBase(), m_id(std::move(id)) {}

QUrl AliasFormViewHost::qmlComponentUrl() const {
  return QUrl(QStringLiteral("qrc:/Vicinae/AliasFormView.qml"));
}

QVariantMap AliasFormViewHost::qmlProperties() {
  return {{QStringLiteral("host"), QVariant::fromValue(this)}};
}

void AliasFormViewHost::initialize() {
  BaseView::initialize();

  auto manager = context()->services->rootItemManager();
  auto meta = manager->itemMetadata(m_id);

  m_alias = QString::fromStdString(meta.alias.value_or(""));
  emit formChanged();

  setNavigationTitle(tr("Set alias - %1").arg(meta.item->title()));
  setNavigationIcon(meta.item->iconUrl());

  auto panel = std::make_unique<FormActionPanelState>();
  auto section = panel->createSection();
  auto submitAction =
      new StaticAction(tr("Submit"), ImageURL::builtin(BuiltinIcon::EnterKey), [this]() { submit(); });
  section->addAction(submitAction);
  setActions(std::move(panel));
}

void AliasFormViewHost::submit() {
  const auto toast = context()->services->toastService();
  const auto manager = context()->services->rootItemManager();

  m_aliasError.clear();
  emit errorsChanged();

  if (manager->setAlias(m_id, m_alias.toStdString())) {
    toast->setToast(tr("Alias modified"), ToastStyle::Success);
    popSelf();
  } else {
    toast->setToast(tr("Failed to modify alias"), ToastStyle::Danger);
  }
}
