/*
 * Copyright © 2015 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * 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/>.
 *
 * Authored by: Alexandros Frantzis <alexandros.frantzis@canonical.com>
 */

#include "unity_screen_service.h"
#include "screen.h"
#include "dbus_message_handle.h"
#include "dbus_event_loop.h"
#include "dbus_connection_handle.h"
#include "scoped_dbus_error.h"

#include "unity_screen_service_introspection.h" // autogenerated

namespace
{

char const* const dbus_screen_interface = "com.canonical.Unity.Screen";
char const* const dbus_screen_path = "/com/canonical/Unity/Screen";
char const* const dbus_screen_service_name = "com.canonical.Unity.Screen";

}

usc::UnityScreenService::UnityScreenService(
    std::shared_ptr<usc::DBusEventLoop> const& loop,
    std::string const& address,
    std::shared_ptr<usc::Screen> const& screen)
    : screen{screen},
      loop{loop},
      connection{std::make_shared<DBusConnectionHandle>(address.c_str())},
      request_id{0}
{
    loop->add_connection(connection);
    connection->request_name(dbus_screen_service_name);
    connection->add_match(
        "type='signal',"
        "sender='org.freedesktop.DBus',"
        "interface='org.freedesktop.DBus',"
        "member='NameOwnerChanged'");
    connection->add_filter(handle_dbus_message_thunk, this);

    screen->register_power_state_change_handler(
        [this](MirPowerMode mode, PowerStateChangeReason reason)
        {
            dbus_emit_DisplayPowerStateChange(mode, reason);
        });
}

::DBusHandlerResult usc::UnityScreenService::handle_dbus_message_thunk(
    ::DBusConnection* connection, DBusMessage* message, void* user_data)
{
    auto const dbus_screen_service = static_cast<usc::UnityScreenService*>(user_data);
    return dbus_screen_service->handle_dbus_message(connection, message, user_data);
}

DBusHandlerResult usc::UnityScreenService::handle_dbus_message(
    ::DBusConnection* connection, DBusMessage* message, void* user_data)
{
    auto const sender = dbus_message_get_sender(message);
    ScopedDBusError args_error;

    if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect"))
    {
        DBusMessageHandle reply{
            dbus_message_new_method_return(message),
            DBUS_TYPE_STRING, &unity_screen_service_introspection,
            DBUS_TYPE_INVALID};

        dbus_connection_send(connection, reply, nullptr);
    }
    else if (dbus_message_is_method_call(message, dbus_screen_interface, "setUserBrightness"))
    {
        int32_t brightness{0};
        dbus_message_get_args(
            message, &args_error, DBUS_TYPE_INT32, &brightness, DBUS_TYPE_INVALID);

        if (!args_error)
        {
            dbus_setUserBrightness(brightness);

            DBusMessageHandle reply{dbus_message_new_method_return(message)};
            dbus_connection_send(connection, reply, nullptr);
        }
    }
    else if (dbus_message_is_method_call(message, dbus_screen_interface, "userAutobrightnessEnable"))
    {
        dbus_bool_t enable{false};
        dbus_message_get_args(
            message, &args_error, DBUS_TYPE_BOOLEAN, &enable, DBUS_TYPE_INVALID);

        if (!args_error)
        {
            dbus_userAutobrightnessEnable(enable);

            DBusMessageHandle reply{dbus_message_new_method_return(message)};
            dbus_connection_send(connection, reply, nullptr);
        }
    }
    else if (dbus_message_is_method_call(message, dbus_screen_interface, "setInactivityTimeouts"))
    {
        int32_t poweroff_timeout{-1};
        int32_t dimmer_timeout{-1};
        dbus_message_get_args(
            message, &args_error,
            DBUS_TYPE_INT32, &poweroff_timeout,
            DBUS_TYPE_INT32, &dimmer_timeout,
            DBUS_TYPE_INVALID);

        if (!args_error)
        {
            dbus_setInactivityTimeouts(poweroff_timeout, dimmer_timeout);

            DBusMessageHandle reply{dbus_message_new_method_return(message)};
            dbus_connection_send(connection, reply, nullptr);
        }
    }
    else if (dbus_message_is_method_call(message, dbus_screen_interface, "setTouchVisualizationEnabled"))
    {
        dbus_bool_t enable{false};
        dbus_message_get_args(
            message, &args_error, DBUS_TYPE_BOOLEAN, &enable, DBUS_TYPE_INVALID);

        if (!args_error)
        {
            dbus_setTouchVisualizationEnabled(enable);

            DBusMessageHandle reply{dbus_message_new_method_return(message)};
            dbus_connection_send(connection, reply, nullptr);
        }
    }
    else if (dbus_message_is_method_call(message, dbus_screen_interface, "setScreenPowerMode"))
    {
        char const* mode = nullptr;
        int32_t reason{-1};

        dbus_message_get_args(
            message, &args_error,
            DBUS_TYPE_STRING, &mode,
            DBUS_TYPE_INT32, &reason,
            DBUS_TYPE_INVALID);

        if (!args_error)
        {
            auto const result = dbus_setScreenPowerMode(mode, reason);
            dbus_bool_t bresult = (result == true);

            DBusMessageHandle reply{
                dbus_message_new_method_return(message),
                DBUS_TYPE_BOOLEAN, &bresult,
                DBUS_TYPE_INVALID};

            dbus_connection_send(connection, reply, nullptr);
        }
    }
    else if (dbus_message_is_method_call(message, dbus_screen_interface, "keepDisplayOn"))
    {
        auto const id = dbus_keepDisplayOn(sender);

        DBusMessageHandle reply{
            dbus_message_new_method_return(message),
            DBUS_TYPE_INT32, &id,
            DBUS_TYPE_INVALID};

        dbus_connection_send(connection, reply, nullptr);
    }
    else if (dbus_message_is_method_call(message, dbus_screen_interface, "removeDisplayOnRequest"))
    {
        int32_t id{-1};
        dbus_message_get_args(
            message, &args_error,
            DBUS_TYPE_INT32, &id,
            DBUS_TYPE_INVALID);

        if (!args_error)
        {
            dbus_removeDisplayOnRequest(sender, id);

            DBusMessageHandle reply{dbus_message_new_method_return(message)};
            dbus_connection_send(connection, reply, nullptr);
        }
    }
    else if (dbus_message_is_signal(message, "org.freedesktop.DBus", "NameOwnerChanged"))
    {
        char const* name = nullptr;
        char const* old_owner = nullptr;
        char const* new_owner = nullptr;

        dbus_message_get_args(
                message, &args_error,
                DBUS_TYPE_STRING, &name,
                DBUS_TYPE_STRING, &old_owner,
                DBUS_TYPE_STRING, &new_owner,
                DBUS_TYPE_INVALID);

        if (!args_error)
            dbus_NameOwnerChanged(name, old_owner, new_owner);
    }
    else if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
    {
         DBusMessageHandle reply{
             dbus_message_new_error(message, DBUS_ERROR_FAILED, "Not supported")};

        dbus_connection_send(connection, reply, nullptr);
    }

    if (args_error)
    {
         DBusMessageHandle reply{
             dbus_message_new_error(message, DBUS_ERROR_FAILED, "Invalid arguments")};

        dbus_connection_send(connection, reply, nullptr);
    }

    return DBUS_HANDLER_RESULT_HANDLED;
}

void usc::UnityScreenService::dbus_setUserBrightness(int32_t brightness)
{
    screen->set_brightness(brightness);
}

void usc::UnityScreenService::dbus_userAutobrightnessEnable(dbus_bool_t enable)
{
    screen->enable_auto_brightness(enable == TRUE);
}

void usc::UnityScreenService::dbus_setInactivityTimeouts(
    int32_t poweroff_timeout, int32_t dimmer_timeout)
{
    screen->set_inactivity_timeouts(poweroff_timeout, dimmer_timeout);
}

void usc::UnityScreenService::dbus_setTouchVisualizationEnabled(dbus_bool_t enable)
{
    screen->set_touch_visualization_enabled(enable == TRUE);
}

bool usc::UnityScreenService::dbus_setScreenPowerMode(
    std::string const& mode,
    int32_t reason)
{
    MirPowerMode new_power_mode;

    // Note: the "standby" and "suspend" modes are mostly unused
    if (mode == "on")
        new_power_mode = MirPowerMode::mir_power_mode_on;
    else if (mode == "standby") // higher power "off" mode (fastest resume)
        new_power_mode = MirPowerMode::mir_power_mode_standby; 
    else if (mode == "suspend") // medium power "off" mode
        new_power_mode = MirPowerMode::mir_power_mode_suspend;
    else if (mode == "off") // lowest power "off" mode (slowest resume)
        new_power_mode = MirPowerMode::mir_power_mode_off;
    else
        return false;

    screen->set_screen_power_mode(
        new_power_mode, static_cast<PowerStateChangeReason>(reason));

    return true;
}

int32_t usc::UnityScreenService::dbus_keepDisplayOn(
    std::string const& sender)
{
    std::lock_guard<std::mutex> lock{keep_display_on_mutex};

    auto const id = ++request_id;

    keep_display_on_ids.emplace(sender, id);
    screen->keep_display_on(true);

    return id;
}

void usc::UnityScreenService::dbus_removeDisplayOnRequest(
    std::string const& sender, int32_t id)
{
    std::lock_guard<std::mutex> lock{keep_display_on_mutex};

    bool id_removed{false};

    auto range = keep_display_on_ids.equal_range(sender);
    for (auto iter = range.first;
         iter != range.second;
         ++iter)
    {
        if (iter->second == id)
        {
            keep_display_on_ids.erase(iter);
            id_removed = true;
            break;
        }
    }

    if (id_removed && keep_display_on_ids.empty())
        screen->keep_display_on(false);
}

void usc::UnityScreenService::dbus_NameOwnerChanged(
    std::string const& name,
    std::string const& old_owner,
    std::string const& new_owner)
{
    if (new_owner.empty() && old_owner == name)
    {
        std::lock_guard<std::mutex> lock{keep_display_on_mutex};
        // If the disconnected client had issued keepDisplayOn requests
        // and after removing them there are now no more requests left,
        // tell the screen we don't need to keep the display on.
        if (keep_display_on_ids.erase(name) > 0 &&
            keep_display_on_ids.empty())
        {
            screen->keep_display_on(false);
        }
    }
}

void usc::UnityScreenService::dbus_emit_DisplayPowerStateChange(
    MirPowerMode power_mode, PowerStateChangeReason reason)
{
    int32_t const power_state = (power_mode == MirPowerMode::mir_power_mode_off) ? 0 : 1;
    int32_t const reason_int = static_cast<int32_t>(reason);

    loop->enqueue(
        [this, power_state, reason_int]
        {
            DBusMessageHandle signal{
                dbus_message_new_signal(
                    dbus_screen_path,
                    dbus_screen_interface,
                    "DisplayPowerStateChange"),
                DBUS_TYPE_INT32, &power_state,
                DBUS_TYPE_INT32, &reason_int,
                DBUS_TYPE_INVALID};

            dbus_connection_send(*connection, signal, nullptr);
        });
}
