#include "MonitorWindow.h"

#include <glib.h>
#include <glib/gi18n.h>
#include "ImageButton.h"

#include "config.h"
#include "Common.h"
#include "UserItem.h"
#include "DmGreeterHelper.h"

MonitorWindow::MonitorWindow(const Glib::RefPtr< Gdk::Monitor >& monitor)
    : Gtk::Window(Gtk::WINDOW_TOPLEVEL)
    , m_monitor(monitor)
    , m_mainlyt()
    , m_background()
    , m_overlay(NULL)
    , m_scaleX(1.0)
    , m_scaleY(1.0) {

    Gdk::Rectangle monitorArea;

    Common::getMonitorScaleFactors(monitor, m_scaleX, m_scaleY);
    monitor->get_geometry(monitorArea);

    this->set_type_hint(Gdk::WINDOW_TYPE_HINT_DESKTOP);
    this->set_keep_below(TRUE);
    this->set_resizable(FALSE);
    setRectangle(monitorArea);

    m_mainlyt.add(m_background);

    if (Common::isPrimary(monitor)) {
        m_overlay = new MainOverLay(&m_mainlyt);
    }

    signal_delete_event().connect(sigc::mem_fun(*this, &MonitorWindow::onWindowDeleteEvent));

    this->add(m_mainlyt);
}

MonitorWindow::~MonitorWindow() {
    if (NULL != m_overlay) {
        delete m_overlay;
        m_overlay = NULL;
    }
}

bool MonitorWindow::isPrimary() {
    return Common::isPrimary(m_monitor);
}

void MonitorWindow::setRectangle(const Gdk::Rectangle& monitorArea) {
    m_monitorArea = monitorArea;

    initBackground();
    this->set_size_request(m_monitorArea.get_width(), m_monitorArea.get_height());
    this->move(m_monitorArea.get_x(), m_monitorArea.get_y());
}

const Glib::RefPtr< Gdk::Monitor >& MonitorWindow::getMonitor() {
    return m_monitor;
}

void MonitorWindow::initBackground() {
    Glib::RefPtr<Gdk::Pixbuf> bgPixbuf = Gdk::Pixbuf::create_from_file(GLOBAL_RES_DIR"/pic/defaultbg.jpg",
                                                                               m_monitorArea.get_width(), m_monitorArea.get_height(),false);
    m_background.set(bgPixbuf);
}

bool MonitorWindow::on_key_press_event(GdkEventKey* event) {
    if (!isPrimary()) {
        return Gtk::Window::on_key_press_event(event);
    }

    if (DmGreeterHelper::inst()->isLoginLocked()) {
        return true;
    }

    if (GDK_KEY_PRESS == event->type) {
        if (NULL != m_overlay && m_overlay->doKeyPressed(event)) {
            return true;
        }
    }
    return Gtk::Window::on_key_press_event(event);
}

bool MonitorWindow::onWindowDeleteEvent(GdkEventAny* event) {
    Gtk::Main::quit();
    return false;
}

bool MonitorWindow::on_enter_notify_event(GdkEventCrossing* crossing_event) {
    if (isPrimary()
        && NULL == m_overlay) {
        m_overlay = new MainOverLay(&m_mainlyt);
        m_mainlyt.show_all();
    }
    
    return Gtk::Window::on_enter_notify_event(crossing_event);
}

bool MonitorWindow::on_leave_notify_event(GdkEventCrossing* crossing_event) {
    if (!isPrimary()
        && NULL != m_overlay) {
        delete m_overlay;
        m_overlay = NULL;
    }
    return Gtk::Window::on_leave_notify_event(crossing_event);
}
