/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 2011  Guillaume DE BURE <guillaume.debure@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    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/>.
*/


#include "incomeexpenditurewidget.h"
#include "skgdocumentbank.h"
#include "skgservices.h"
#include "skgmainpanel.h"
#include <Plasma/Label>
#include <KMessageBox>

#include <QGraphicsLinearLayout>
#include <Plasma/Meter>
#include <Plasma/IconWidget>


IncomeExpenditureWidget::IncomeExpenditureWidget(QObject* iParent, const QVariantList& args):
    Applet(iParent, args), widgetLayout(NULL)
{}

IncomeExpenditureWidget::~IncomeExpenditureWidget()
{}

void IncomeExpenditureWidget::init()
{
    if (widgetLayout == NULL) {
        // This is the layout for the whole widget
        widgetLayout = new QGraphicsLinearLayout(Qt::Vertical);
        setLayout(widgetLayout);

        Plasma::DataEngine* engine = dataEngine("skgdataengine");
        if (engine->isValid()) {
            engine->connectSource("IncomesExpenditures", this);
        }
    }
}

void IncomeExpenditureWidget::dataUpdated(const QString& sourceName, const Plasma::DataEngine::Data& engineData)
{
    if (sourceName != "IncomesExpenditures") {
        return;
    }
    QHash<QString, QStringList> listData;
    for (int i = 0 ; i < engineData.keys().count() ; ++i) {
        QString keyId = engineData.keys().at(i);
        QVariant valuesVariant = engineData.value(keyId);
        QStringList values = valuesVariant.value<QStringList>();

        listData[keyId] = values;
    }

    // Get the max abs value for amounts
    double max = 0;
    for (int i = 0 ; i < listData.count() ; i++) {
        QStringList values = listData.values().at(i);
        double amount = qAbs(SKGServices::stringToDouble(values.at(2)));
        if (amount > max) {
            max = amount;
        }
    }

    // Get the current document
    SKGMainPanel* panel = SKGMainPanel::getMainPanel();
    SKGDocumentBank* doc = qobject_cast<SKGDocumentBank*> (panel->getDocument());

    // Get the primary unit
    primary = doc->getPrimaryUnit();


    // Remove all elements in the current layout, so that we start with a fresh
    // widget when data is updated
    int nb = widgetLayout->count();
    for (int i = 0; widgetLayout && i < nb; ++i) {
        QGraphicsLayoutItem* item = widgetLayout->itemAt(0);
        if (item) {
            widgetLayout->removeAt(0);
            delete item;
        }
    }

    QHash<QString, Plasma::Frame*> frames;

    for (int i = 0; i < listData.count(); ++i) {
        // Operation id
        QString keyId = listData.keys().at(i);

        QStringList values = listData[keyId];

        // Month
        QString date = values.at(0);

        // Type
        QString type = values.at(1);

        // Amount
        double amount = SKGServices::stringToDouble(values.at(2));


        Plasma::Frame* monthFrame;
        if (not frames.keys().contains(date)) {
            // If the frame does not exist yet for this date we create it
            // and we store it in the hash
            monthFrame = new Plasma::Frame();
            monthFrame->setFrameShadow(Plasma::Frame::Raised);
            widgetLayout->addItem(monthFrame);
            QGraphicsLinearLayout* frameLayout = new QGraphicsLinearLayout(Qt::Vertical);
            monthFrame->setLayout(frameLayout);
            Plasma::Label* dateLabel = new Plasma::Label();
            dateLabel->setText(date);
            QFont dateLabelFont = dateLabel->font();
            dateLabelFont.setBold(true);
            dateLabel->setFont(dateLabelFont);
            frameLayout->addItem(dateLabel);
            frames[date] = monthFrame;
        } else {
            // If the frame already exist, we just reuse it
            monthFrame = frames[date];
        }

        // Add a line in the applet
        QGraphicsLinearLayout* lineLayout = static_cast< QGraphicsLinearLayout* >(monthFrame->layout());
        QGraphicsLinearLayout* meterLayout = new QGraphicsLinearLayout(Qt::Horizontal);
        lineLayout->addItem(meterLayout);


        // Create an IconWidget for the type of value (income or expense)
        Plasma::IconWidget* typeIcon = new Plasma::IconWidget();
        if (type == "+") {
            typeIcon->setIcon("list-add");  // Type income
        } else {
            typeIcon->setIcon("list-remove");  // Type expense
        }
        typeIcon->setMaximumIconSize(QSizeF(18, 18));
        meterLayout->addItem(typeIcon);

        Plasma::Meter* amountMeter = new Plasma::Meter();
        meterLayout->addItem(amountMeter);
        amountMeter->setPreferredWidth(100);
        amountMeter->setMaximumHeight(18);
        amountMeter->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
        amountMeter->setMinimum(0);
        amountMeter->setMaximum(max);
        amountMeter->setValue(qAbs(int(amount)));
        amountMeter->setMeterType(Plasma::Meter::BarMeterVertical);
        amountMeter->setToolTip(SKGServices::doubleToString(amount));
    }

    widgetLayout->addStretch(40);
}

#include "incomeexpenditurewidget.moc"
