/* -*- c++ -*-
 *
 * shareinfo.cpp
 *
 * Copyright (C) 2003 Petter Stokke <ummo@hellokitty.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 2
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include "shareinfo.h"
#include "donkeymessage.h"
#include "fileinfo.h"

#include <qfile.h>
#include <qregexp.h>

ShareInfo::ShareInfo(DonkeyMessage* msg, int proto)
{
    num = msg->readInt32();
    network = msg->readInt32();
    QByteArray ba = msg->readByteArray();
    ba.resize(ba.size() + 1); ba[ba.size()-1] = 0;
    name = QFile::decodeName( QCString( ba.data(), ba.size() ) ); // the file is locally encoded
    size = msg->readInt64();
    uploaded = msg->readInt64();
    requests = msg->readInt32();
    uids.clear();
    if (msg->opcode() >= 48) {
        if (proto >= 31) {
            for (int i = msg->readInt16(); i; i--)
                uids.append(msg->readString());
        } else {
            QByteArray md4(16);
            for (int i = 0; i < 16; i++)
                md4[i] = msg->readInt8();
            uids.append(QString("urn:ed2k:") + FileInfo::md4ToString(md4));
        }
    }
}

ShareInfo::ShareInfo(const ShareInfo& si)
{
    num = si.shareNo();
    network = si.shareNetwork();
    name = si.shareName();
    size = si.shareSize();
    uploaded = si.shareUploaded();
    requests = si.shareRequests();
    uids = si.shareUids();
}

ShareInfo::~ShareInfo()
{
}

void ShareInfo::updateShare(DonkeyMessage* msg, int)
{
    uploaded = msg->readInt64();
    requests = msg->readInt32();
}

const int ShareInfo::shareNo() const { return num; }
const int ShareInfo::shareNetwork() const { return network; }
const QString& ShareInfo::shareName() const { return name; }
const int64 ShareInfo::shareSize() const { return size; }
const int64 ShareInfo::shareUploaded() const { return uploaded; }
const int ShareInfo::shareRequests() const { return requests; }

const QStringList& ShareInfo::shareUids() const
{
    return uids;
}

QString ShareInfo::shareUid() const
{
    return uids.first();
}

QString ShareInfo::shareUid(const QString& type) const
{
    QRegExp match(QString("^urn:") + type + ":");
    QStringList results = uids.grep(match);
    if (!results.count()) return QString::null;
    QString result(results.first());
    result.replace(match, "");
    return result;
}

