/* ====================================================================
 * Copyright (c) 2003-2007, Martin Hauner
 *                          http://subcommander.tigris.org
 *
 * Subcommander is licensed as described in the file doc/COPYING, which
 * you should have received as part of this distribution.
 * ====================================================================
 */

// sc
#include "config.h"
#include "DragDrop.h"
#include "util/apr.h"

// qt
#include <QtCore/QMimeData>

// svn
#include <svn_path.h>


QStringList decodeDropData( const QMimeData* data )
{
  QStringList result;

  if( data->hasFormat("text/uri-list") )
  {
    QByteArray bytes = data->data("text/uri-list");

    // extract all strings seperated by \r\n

    // cleanup %xx
    apr::Pool pool;
    const char* tmp  = svn_path_uri_decode(bytes.data(),pool);
    QString     drop = QString::fromUtf8(tmp);

    // cleanup path seperator
    drop.replace( "\\", "/" );

    for( int i = 0; true; i++ )
    {
      QString item = drop.section( "\r\n", i, i );

      if( item.isEmpty() )
      {
        break;
      }
      
      // MacOSX has a '/' at the end of an url, remove it.
      if( item.endsWith("/") && item.length() > 1 )
      {
        item = item.left(item.length()-1);
      }
      
      result.push_back(item);
    }
  }
  // windows: firefox
  else if( data->hasFormat("text/plain") )
  {
    QByteArray bytes = data->data("text/plain");

    // extract a single string until we hit a linefeed
    QString text(bytes);
    QString item = text.section( "\n", 0, 0 );
    result.push_back(item);
  }
  else
  {
    result.push_back( _q("unknown drag & drop format") );
  }

  return result;
}

QStringList decodeDropText( const QString& text, const QString& format )
{
  QStringList result;

  // windows: explorer/iexplore/totalcommander
  if( format == QString("text/uri-list") )
  {
    // extract all strings seperated by \r\n

    // cleanup %xx
    const char* tmp  = svn_path_uri_decode(text.toUtf8(),apr::Pool());
    QString     drop = QString::fromUtf8(tmp);

    // cleanup path seperator
    drop.replace( "\\", "/" );

    for( int i = 0; true; i++ )
    {
      QString item = drop.section( "\r\n", i, i );

      if( item.isEmpty() )
      {
        break;
      }
      
      // MacOSX has a '/' at the end of an url, remove it.
      if( item.endsWith("/") && item.length() > 1 )
      {
        item = item.left(item.length()-1);
      }
      
      result.push_back(item);
    }
  }
  // windows: firefox
  else if( format.contains("text/plain") == 1 )
  {
    // extract a single string until we hit a linefeed
    QString item = text.section( "\n", 0, 0 );
    result.push_back(item);
  }
  else
  {
    result.push_back( _q("unknown drag & drop format") );
  }

  return result;
}
