/***************************** LICENSE START ***********************************

 Copyright 2016 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/


#include <QApplication>
#include <QStyleFactory>
#include <stdio.h>
#include "mars.h"
#include "MvRequest.h"
#include "XServ.h"


XServBar::XServBar(svc* s)
{
    service_ = s;

    setLayout(&layoutMain_);
    layoutMain_.addWidget(&scrollArea_);
    scrollAreaInternalWidget_ = new QWidget(this);
    scrollAreaInternalWidget_->setLayout(&buttonLayout_);
    scrollArea_.setWidget(scrollAreaInternalWidget_);
    scrollArea_.setWidgetResizable(true);
    move(0, 0);  // set the window to the top-left of the screen


    // populate the bar with buttons - one for each available service
    request* r = mars.setup;
    int n = 0;
    while (r) {
        if (strcmp(r->name, "service") == 0) {
            const char* y = no_quotes(get_value(r, "name", 0));
            auto* button = new QPushButton(QString(y), this);
            buttonLayout_.addWidget(button, n % 25, n / 25);
            connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
            n++;
        }
        r = r->next;
    }


    QSizePolicy sp(QSizePolicy::Preferred, QSizePolicy::Preferred);
    scrollAreaInternalWidget_->setSizePolicy(sp);
    updateGeometry();


    show();
    scrollArea_.show();

    QRect rect = buttonLayout_.cellRect(0, 1);

    QPoint tl = rect.topLeft();
    QPoint qp = scrollAreaInternalWidget_->mapTo(this, tl);
    // QScrollBar *sb = scrollArea_.verticalScrollBar();
    // wsize = qp.x() + rect.right() + sb->width();
    int wsize = qp.x() + 22;  // sb->width();
    resize(wsize, 400);
}


void XServBar::buttonClicked()
{
    auto* button = (QPushButton*)sender();
    QString name(button->text());
    // printf("CLICKED: %s\n", name.toUtf8().constData());

    request* r = empty_request("START");
    set_value(r, "NAME", "%s", name.toUtf8().constData());
    call_switchboard(service_, r);
    free_all_requests(r);
}


int main(int argc, char** argv)
{
    QApplication qapp(argc, argv);
    // TODO: use MvQTheme here!
    // QApplication::setWindowIcon(QIcon(MvQTheme::logo()));


    // Get qt style
    char* styleCh = getenv("METVIEW_QT_STYLE");
    if (styleCh) {
        QString style(styleCh);

        QStringList styleLst = QStyleFactory::keys();
        if (styleLst.contains(style)) {
            qapp.setStyle(style);
        }
    }

    marsinit(&argc, argv, nullptr, 0, nullptr);

    svc* s = create_service(mbasename(argv[0]));
    if (s)
        svc_connect(s);

    XServBar bar(s);

    return qapp.exec();
}
