// Copyright 2010-2021, 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:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. 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 THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT
// OWNER OR 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.

#include "unix/ibus/ibus_config.h"

#include <string>
#include <utility>
#include <vector>

#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "base/file_util.h"
#include "base/protobuf/text_format.h"
#include "base/system_util.h"
#include "unix/ibus/ibus_config.pb.h"
#include "unix/ibus/main.h"

namespace mozc {

constexpr char kIbusConfigFile[] = "ibus_config.textproto";

namespace {
std::string UpdateConfigFile() {
  const std::string engines_file = FileUtil::JoinPath(
      SystemUtil::GetUserProfileDirectory(), kIbusConfigFile);
  if (absl::Status s = FileUtil::FileExists(engines_file); s.ok()) {
    absl::StatusOr<std::string> config = FileUtil::GetContents(engines_file);
    if (!config.ok()) {
      LOG(ERROR) << config.status();
      return kIbusConfigTextProto;
    }
    return *std::move(config);
  } else if (absl::IsNotFound(s)) {
    if (absl::Status s =
            FileUtil::SetContents(engines_file, kIbusConfigTextProto);
        !s.ok()) {
      LOG(ERROR) << "Failed to write " << engines_file << ": " << s;
    }
    return kIbusConfigTextProto;
  } else {
    LOG(ERROR) << "Cannot check if " << engines_file << "exists: " << s;
    return kIbusConfigTextProto;
  }
}

std::string NormalizeLayout(const std::string &layout) {
  std::string output;
  for (const char c : layout) {
    if (absl::ascii_isalnum(c) || c == '_' || c == '-' || c == '/') {
      output += c;
    } else {
      output += '_';
    }
  }
  return output;
}

bool ParseConfig(const std::string &data, ibus::Config &config) {
  const bool success =
      mozc::protobuf::TextFormat::ParseFromString(data, &config);
  if (!success) {
    // Failed to parse the data, fallback to the default setting.
    mozc::protobuf::TextFormat::ParseFromString(kIbusConfigTextProto, &config);
  }

  for (ibus::Engine &engine : *config.mutable_engines()) {
    engine.set_layout(NormalizeLayout(engine.layout()));
    engine.set_layout_variant(NormalizeLayout(engine.layout_variant()));
    engine.set_layout_option(NormalizeLayout(engine.layout_option()));
  }
  return success;
}

std::string EscapeXmlValue(const std::string &value) {
  return absl::StrReplaceAll(value, {{"&", "&amp;"},
                                     {"<", "&lt;"},
                                     {">", "&gt;"},
                                     {"\"", "&quot;"},
                                     {"'", "&apos;"}});
}

std::string CreateEnginesXml(const ibus::Config &config) {
  std::string output = "<engines>\n";
  for (const ibus::Engine &engine : config.engines()) {
    // clang-format off
    absl::StrAppend(
        &output,
        "<engine>\n",
        "  <description>", kEngineDescription, "</description>\n",
        "  <language>", kEngineLanguage, "</language>\n",
        "  <icon>", kEngineIcon, "</icon>\n",
        "  <rank>", engine.rank(), "</rank>\n",
        "  <icon_prop_key>", kEngineIcon_prop_key, "</icon_prop_key>\n",
        "  <symbol>", EscapeXmlValue(engine.symbol()), "</symbol>\n",
        "  <setup>", kEngineSetup, "</setup>\n",
        "  <name>", EscapeXmlValue(engine.name()), "</name>\n",
        "  <longname>", EscapeXmlValue(engine.longname()), "</longname>\n",
        "  <layout>", engine.layout(), "</layout>\n",
        "  <layout_variant>", engine.layout_variant(), "</layout_variant>\n",
        "  <layout_option>", engine.layout_option(), "</layout_option>\n",
        "</engine>\n");
    // clang-format on
  }
  absl::StrAppend(&output, "</engines>\n");
  return output;
}
}  // namespace

bool IbusConfig::Initialize() {
  const std::string config_data = UpdateConfigFile();
  return LoadConfig(config_data);
}

bool IbusConfig::LoadConfig(const std::string &config_data) {
  const bool valid_user_config = ParseConfig(config_data, config_);

  engine_xml_ = CreateEnginesXml(config_);
  if (!valid_user_config) {
    engine_xml_ +=
        ("<!-- Failed to parse the user config. -->\n"
         "<!-- Used the default setting instead. -->\n");
  }

  return valid_user_config;
}

const std::string &IbusConfig::GetEnginesXml() const { return engine_xml_; }

const ibus::Config &IbusConfig::GetConfig() const { return config_; }

const std::string &IbusConfig::GetLayout(absl::string_view name) const {
  for (const ibus::Engine &engine : config_.engines()) {
    if (engine.name() == name) {
      return engine.layout();
    }
  }
  return default_layout_;
}

ibus::Engine::CompositionMode IbusConfig::GetCompositionMode(
    absl::string_view engine_name) const {
  for (const ibus::Engine &engine : config_.engines()) {
    if (engine.name() == engine_name) {
      return engine.composition_mode();
    }
  }
  return ibus::Engine::NONE;
}

bool IbusConfig::IsActiveOnLaunch() const {
  if (config_.has_active_on_launch()) {
    return config_.active_on_launch();
  }

  // The default value is off as IBus team's recommentation.
  // https://github.com/google/mozc/issues/201
  return false;
}

bool IbusConfig::IsMozcRendererEnabled() const {
  if (!config_.has_mozc_renderer()) {
    return true;
  }
  return config_.mozc_renderer().enabled();
}

std::vector<std::string>
IbusConfig::GetMozcRendererCompatibleWaylandDesktopNames() const {
  if (!config_.has_mozc_renderer()) {
    return {};
  }
  const auto &desktop_names =
      config_.mozc_renderer().compatible_wayland_desktop_names();
  return {desktop_names.begin(), desktop_names.end()};
}

}  // namespace mozc
