
#include "MainWindow.h"
#include "Common.h"

#include <syslog.h>

MainWindow::MainWindow()
    : m_monitorWin() {
}

MainWindow::~MainWindow() {

}

void MainWindow::initialize() {
    Glib::RefPtr< Gdk::Display > defaultDisplay = Gdk::Display::get_default();
    Glib::RefPtr< Gdk::Screen > defaultScreen = Gdk::Screen::get_default();

    m_monitorAddIter = defaultDisplay->signal_monitor_added().connect(sigc::mem_fun(*this, &MainWindow::onMonitorAdd));
    m_monitorsChangedIter = defaultScreen->signal_monitors_changed().connect(sigc::mem_fun(*this, &MainWindow::onMonitorsChanged));
    initMonitors();
}

void MainWindow::finalize() {
    while (!m_monitorWin.empty()) {
        MonitorWindow* win = m_monitorWin.back();
        if (win) {
            delete win;
            win = NULL;
        }
        m_monitorWin.pop_back();
    }

    m_monitorAddIter.disconnect();
    m_monitorsChangedIter.disconnect();
}

void MainWindow::initMonitors() {
    Glib::RefPtr< Gdk::Display > defaultDisplay = Gdk::Display::get_default();
    for (int i = 0; i < defaultDisplay->get_n_monitors(); ++i) {
        m_monitorWin.push_back(new MonitorWindow(defaultDisplay->get_monitor(i)));
    }
}

void MainWindow::recreateMonitors() {
    while (!m_monitorWin.empty()) {
        MonitorWindow* win = m_monitorWin.back();
        if (win) {
            delete win;
            win = NULL;
        }
        m_monitorWin.pop_back();
    }
    initMonitors();
}

void MainWindow::onMonitorAdd(const Glib::RefPtr< Gdk::Monitor >& monitor) {
    
    Glib::RefPtr< Gdk::Display > defaultDisplay = Gdk::Display::get_default();
    Glib::RefPtr< Gdk::Screen > defaultScreen = Gdk::Screen::get_default();

    m_monitorAddIter = defaultDisplay->signal_monitor_added().connect(sigc::mem_fun(*this, &MainWindow::onMonitorAdd));
    m_monitorsChangedIter = defaultScreen->signal_monitors_changed().connect(sigc::mem_fun(*this, &MainWindow::onMonitorsChanged));

    int i = defaultDisplay->get_n_monitors();

    const Glib::RefPtr< Gdk::Monitor >& new_monitor = defaultDisplay->get_monitor(i);
    
    m_monitorWin.push_back(new MonitorWindow(new_monitor));
    
    openlog("login-debug", LOG_CONS | LOG_PID, 0);
    //syslog(LOG_USER | LOG_INFO, "receive onMonitorAdd: width:%d, height:%d----------\n",width, height);
    syslog(LOG_USER | LOG_INFO, "receive onMonitorAdd-------\n");
    show_all();
    closelog();
}

void MainWindow::onMonitorsChanged() {
    recreateMonitors();
    show_all();
}

void MainWindow::show_all() {
    for (int i = 0; i < m_monitorWin.size(); ++i) {
        m_monitorWin[i]->show_all();
    }
}
