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

 Copyright 2013 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 <QMimeData>
#include <QByteArray>
#include <QDataStream>
#include <QDropEvent>

#include "MvQDragDrop.h"

MvQDrop::MvQDrop(QDropEvent* event) :
    dataType_(NoData)
{
    if (event->proposedAction() != Qt::CopyAction &&
        event->proposedAction() != Qt::MoveAction) {
        return;
    }

    else if (event->mimeData()->hasFormat("metview/icon") ||
             event->mimeData()->hasFormat("metview/feature")) {
        parseMimeData(event->mimeData());
    }
}

MvQDrop::MvQDrop(QMimeData* data) :
    dataType_(NoData)
{
    parseMimeData(data);
}

void MvQDrop::parseMimeData(const QMimeData* data)
{
    dataType_ = NoData;

    Q_ASSERT(data);
    // icon drop from desktop
    if (data->hasFormat("metview/icon")) {
        QByteArray encodedData = data->data("metview/icon");
        QDataStream stream(&encodedData, QIODevice::ReadOnly);

        QString text;
        stream >> text;
        int num = text.toInt();

        if (num <= 0 || num > 20) {
            return;
        }

        int cnt = 0;
        while (!stream.atEnd()) {
            stream >> text;
            if (cnt % 2 == 0)
                iconPath_ << text;
            else
                iconClass_ << text;

            cnt++;
        }

        if (num != iconPath_.count() || num != iconClass_.count()) {
            return;
        }

        dataType_ = IconData;
    }
    // symbol icon drop in uplot
    else if (data->hasFormat("metview/feature")) {
        QByteArray encodedData = data->data("metview/feature");
        QDataStream stream(&encodedData, QIODevice::ReadOnly);

        while (!stream.atEnd()) {
            QString key, val;
            stream >> key >> val;
            values_[key] = val;
        }

        dataType_ = FeatureData;
    }
}

QString MvQDrop::iconPath(int i) const
{
    return (i >= 0 && i < iconPath_.count()) ? iconPath_.at(i) : QString();
}

QString MvQDrop::iconClass(int i) const
{
    return (i >= 0 && i < iconPath_.count()) ? iconClass_.at(i) : QString();
}
