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

void MvQIconDropItem::appendToFullName(string s)
{
	fullName_=fullName_.append(s);
}

void MvQIconDropItem::finalizeFullName()
{
	fullName_.erase(fullNameLen_,fullName_.size()-fullNameLen_);
}

void MvQIconDropItem::clear()
{
	name_.clear();
	class_.clear();
	fullName_.clear();
	fullNameLen_ = 0;
	x_= y_       = 0;
	winId_       = 0;
	count_       = 0;
//	totalNum_    = 0;
	batchNum_    = 0;
	format_      = 0;
	iconId_      = 0;
}


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

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

MvQDrop::MvQDrop(QMimeData *data) : hasData_(false)
{
   parseMimeData(data);
}

void MvQDrop::parseMimeData(const QMimeData *data)           
{
   Q_ASSERT(data);
   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)
      {
         hasData_=false;
         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())
      {
         hasData_=false;
         return;
      }

      hasData_=true;

   }
   else
   {
      hasData_=false;
   }
}

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();
}
