#include <QString>
#include <kdebug.h>
#include "ttgview.h"
#include "newmusicbrainzdialog.h"
#include "musicbrainzservice.h"
#include "artistquery.h"

TtgView::TtgView(QWidget *parent) : QWidget(parent)
{
   setupUi(this);
   
   setupTree();
   
   //*** START the theory is here we'd start a loop for each service plugin loaded...
   
   kDebug() << "Adding service " << TtgView::MUSICBRAINZ;
   //init the musicbrainz service and add it to the drop down
   addServiceType(i18n("Musicbrainz Query"), initService(TtgView::MUSICBRAINZ));
   //connect up the service interface signal and the local add slot
   connect(btnAddQuery, SIGNAL(clicked()), this, SLOT(addQueryClicked()));
   
   //** END of theoretical loop through plugins
}

void TtgView::addServiceType(QString serviceTypeName, int serviceId)
{
   cmbService->addItem(serviceTypeName, serviceId);
   addTreeServiceHeading(serviceId, serviceTypeName);
}

void TtgView::addQueryClicked()
{
   NewMusicbrainzDialog nmd;
   nmd.exec();
   QString txt = nmd.getSearchText();
   
   addQuery(TtgView::MUSICBRAINZ, txt);
}

int TtgView::addQuery(ServiceType serviceType, QString searchText)
{
   KMusicbrainz::ArtistQuery* artistQuery = new KMusicbrainz::ArtistQuery(m_services[serviceType], this);
   artistQuery->setSearchName( searchText );
   int qId = m_qm.addQuery( artistQuery, m_managedServiceIdList[serviceType] );
   
   addTreeQueryItem(m_managedServiceIdList[serviceType], qId, searchText);
   
   btnStartPause->setEnabled(true);
   connect(btnStartPause, SIGNAL(clicked()), this, SLOT(startClicked()));
   
   kDebug() << "About to return " << qId;
   
   return qId;
}

int TtgView::initService(ServiceType serviceType)
{
   m_services[serviceType] = new KMusicbrainz::MusicbrainzService(this);
   m_managedServiceIdList[serviceType] = m_qm.createServiceQueue(m_services[serviceType], serviceType);
   return m_managedServiceIdList[serviceType];
}

void TtgView::setupTree()
{
   treeWidget->setColumnCount(1);
   treeWidget->setHeaderLabel(i18n("Service Queues"));
}

void TtgView::addTreeServiceHeading(int id, const QString &heading)
{
   QTreeWidgetItem* item = new QTreeWidgetItem(treeWidget, QTreeWidgetItem::Type);
   item->setText(0, heading);
   treeWidget->insertTopLevelItem(id, item);
}

void TtgView::addTreeQueryItem(int serviceHeadingId, int queryId, const QString &searchText)
{
   QTreeWidgetItem* tli = treeWidget->topLevelItem(serviceHeadingId);
   QTreeWidgetItem* item = new QTreeWidgetItem(tli, QTreeWidgetItem::Type);
   item->setText(0, searchText);
}

void TtgView::startClicked()
{
   QHash < ServiceType, ServiceModel::Service* >::const_iterator i = m_services.constBegin();
   while (i != m_services.constEnd()) {
      if (!m_qm.isProcessing(i.key())) {
         kDebug() << "this is the key: " << i.key();
         m_qm.startQueue(i.key());
      }
      ++i;
   }
}

