/*
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: 
*
*/
#include "zeroconfsharing.h"
#include <mdns/mdnsparamset.h>

#include <QtGui/QListWidget>
#include <QVBoxLayout>
#include <QtNetwork>
#include <QNetworkRequest>
#include <QNetworkReply>

#ifdef Q_OS_SYMBIAN
#include "sym_iap_util.h"
#endif
#include "bjrhttpserver.h"

#include "contactinfo.h"
#include "cfileparser.h"
#include "cfilelistengine.h"
#include "downloadicon.h"
_LIT8(KFileName,"E:\\logs\\temp.txt");

_LIT8(KMyStatusFile,"E:\\MyStatus.txt");
const int KMaxLength = 256;
_LIT8(KLogFile,"E:\\logs\\uilog.txt");

QZeroConfSharingUi::QZeroConfSharingUi(QWidget *parent)
    : QMainWindow(parent)
    {
	ui.setupUi(this);
	
	isShared = false;
	
    tabWidget = new QTabWidget(this);
    tabWidget->hide();
    
    shareAction = new QAction(tr("Share"), this);
    connect(shareAction, SIGNAL(triggered()), this, SLOT(StartServer()));
    
    unshareAction = new QAction(tr("UnShare"), this);
    connect(unshareAction, SIGNAL(triggered()), this, SLOT(StopServer()));
    
    menuBar()->addAction(shareAction);
#ifdef Q_OS_SYMBIAN
       qt_SetDefaultIap();
#endif
   
    manager = new QNetworkAccessManager(this);
    
#ifndef __arm 
    PopulateCommunityList();
    PopulateCommunityList();
    PopulateCommunityList();
    PopulateCommunityList();
    PopulateCommunityList();
#endif
    // Hide the Contact Tab
    ui.tabWidget->removeTab(0);
    // Hide the Chat tab
    ui.tabWidget->removeTab(4);
    // Hide the File Share Tab
    ui.treeContactMusic->setVisible(false);
    ui.treeContactMusic_2->setVisible(false);
    ui.treeContactMusic_3->setVisible(false);
    
    ShowBackButtons(false);
    // Layout
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(ui.tabWidget);
    setLayout(layout);   


	ui.tabWidget->setContextMenuPolicy(Qt::NoContextMenu);
    ui.tabWidget->showMaximized();

    connect(ui.listAvatars, SIGNAL(itemClicked(QListWidgetItem *)),
            this, SLOT(on_listAvatars_itemClicked(QListWidgetItem *)));   
  
	ui.tabWidget->setCurrentIndex(0);
	
	connect(ui.StatusUpdatebtn, SIGNAL(pressed()),this,SLOT(UpdateMyStatus()));
    connect(ui.pushBackContact, SIGNAL(clicked ()), this, SLOT(backPressed()));
    connect(ui.pushBackPhoto, SIGNAL(clicked ()), this, SLOT(backPressed()));
    connect(ui.pushBackVideo, SIGNAL(clicked ()), this, SLOT(backPressed()));
    connect(ui.pushBackChat, SIGNAL(clicked ()), this, SLOT(backPressed()));
    connect(ui.pushBackMusic, SIGNAL(clicked ()), this, SLOT(backPressed()));
	
    connect(ui.treeContactMusic_2, SIGNAL(itemClicked(QTreeWidgetItem* , int)), this, SLOT(ContactitemClicked(QTreeWidgetItem* , int)));
    connect(ui.treeContactMusic, SIGNAL(itemClicked(QTreeWidgetItem* , int)), this, SLOT(ContactitemClicked(QTreeWidgetItem* , int)));
    connect(ui.treeContactMusic_3, SIGNAL(itemClicked(QTreeWidgetItem* , int)), this, SLOT(ContactitemClicked(QTreeWidgetItem* , int)));
    
	//Open the status file
    QString mystatusfile = QString::fromUtf8((const char*)KMyStatusFile().Ptr(),KMyStatusFile().Length());
    bool doesExist = MyStatusFile.exists(mystatusfile);
    MyStatusFile.setFileName(mystatusfile);
    //file already exists...get the status from file
    MyStatusFile.open( QIODevice::ReadOnly|QIODevice::Text );
    //opened in write only mode so that status updates can be
    //reflected in the file
    QByteArray str = MyStatusFile.readAll();
    QString filestr(str);
    nowStatus = filestr;
           
    ui.MyStatusLabel->setText(nowStatus);
    
    //convert nowSttaus to Rbuf8
    TPtrC ptrName(reinterpret_cast<const TText*>(nowStatus.constData()));

    iStatus.CreateL(ptrName.Length());
    iStatus.Copy(ptrName);
   
	
	iZeroConfClient = CZeroconfClient::NewL(this);
    iZeroConfClient->ConnectL();
    
    iNewContact = NULL;
       MyStatusFile.close();
       
       iStatusUpdate =EFalse;
    
    iMusic = CMusicProvider::NewL(this);    
    iUpdate = EFalse;
    iMusic->RequestMediaL();
    
    DiscoverServices();
	
    progressBar = NULL;
    //IsDownloadItem = false;
    
    logFile.setFileName("C:\\Data\\logs\\ZeroConfSharingui_log.txt");
    logFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
    
    logFile.write("Logging Starts");        
    logFile.close();

    
    }

void QZeroConfSharingUi::Log(const char* msg)
    {

    logFile.open(QIODevice::Append);
    logFile.write(msg, qstrlen(msg));        
    logFile.close();

    }


void QZeroConfSharingUi::ContactitemClicked(QTreeWidgetItem* item, int /*column*/)
    {
    
    TPtrC ptrName(reinterpret_cast<const TText*>(iSelectedContact.constData()));
      
    RBuf8 contactName;
    contactName.Create(ptrName.Length());
    contactName.Copy(ptrName);

    //Find if its an already existing contact
    CContactInfo* contact = GetSelectedContact(contactName);
    if(contact!=NULL)
        {
        //IsDownloadItem = true;
        RBuf8 url;
        url.Create(KMaxLength);
        url.Copy(contact->BaseUrl());
        
        TPtrC fileItemName(reinterpret_cast<const TText*>((item->text(0)).constData()));
        
        RBuf8 fileName;
        fileName.Create(fileItemName.Length());
        fileName.Copy(fileItemName);
        
        url.Append(fileName);
        
        QString qurl = QString::fromUtf8((const char*)url.Ptr(),url.Length());
        
        iSelectedFileName = QString::fromUtf8((const char*)(contact->FilePath(fileName)).Ptr(),(contact->FilePath(fileName)).Length());
        
        progressBar = new QProgressDialog(tr("Retrieving Shared Content"), tr("Cancel"), 0, 0);
        connect(progressBar, SIGNAL(canceled()), this, SLOT(ProgressBarCanceled()));
        progressBar->show();
    
        itemReply = manager->get(QNetworkRequest(QUrl(qurl)));
    
        connect(itemReply, SIGNAL(finished()), this, SLOT(ItemRequestFinished()));
        
        fileName.Close();
        url.Close();
        
        }
    contactName.Close();
    
    }


void QZeroConfSharingUi::UpdateMyStatus()
    {
    //get the Text entered by the user in the status update
    //text box
    //& display it in the MyStatus label button
    
    QString mystatusfile = QString::fromUtf8((const char*)KMyStatusFile().Ptr(),KMyStatusFile().Length());
    bool doesExist = MyStatusFile.exists(mystatusfile);
    MyStatusFile.setFileName(mystatusfile);
    
    MyStatusFile.open( QIODevice::WriteOnly |QIODevice::Text );
    QString currentStatus = ui.StatusTextBox->toPlainText();
    //set the MyStatusLabel with this text
    ui.MyStatusLabel->setText(currentStatus);
    nowStatus = currentStatus;
    TPtrC ptrName(reinterpret_cast<const TText*>(nowStatus.constData()));
            
    RBuf8 current;
    current.Create(ptrName.Length());
    current.Copy(ptrName);
    if(iStatusUpdate)
        {
        iZeroConfClient->UpdateCurrentStatusServiceL(current);
        }
    else
        {
        iZeroConfClient->PublishCurrentStatusServiceL(current);
        iStatusUpdate =ETrue;
        }
    
    int errval = MyStatusFile.write(nowStatus.toUtf8());
    MyStatusFile.close();
    current.Close();
    ui.StatusTextBox->clear();    
    //send an update record at Bonjour-level
        
    }

void QZeroConfSharingUi::PopulateCommunityList()
{
    static int i = 0;
    QString path, name;
    switch(i)
    {
        case 0:  path = ":/Images/Vivek"; name = "Vivek";break;
        case 1:  path = ":/Images/Unknown"; name = "Vadan";break;
        case 2:  path = ":/Images/Guru"; name = "Guru"; break;
        case 3:  path = ":/Images/Sampo"; name =  "Sampo";break;
        case 4:  path = ":/Images/Unknown"; name = "Sindhu";break;
        default: break;
    }
    i++;
    QListWidgetItem* item = new QListWidgetItem(QIcon(path), name);
    ui.listAvatars->addItem(item);
}

void QZeroConfSharingUi::PopulateUserList()
{
}
void QZeroConfSharingUi::backPressed()
    {
    ShowAllContacts(true);
    setWindowTitle(QApplication::translate("MainWindow", "Local Sharing", 0, QApplication::UnicodeUTF8));
    
    ui.treeContactMusic->setVisible(false);
    ui.treeContactMusic_2->setVisible(false);
    ui.treeContactMusic_3->setVisible(false);

    ui.treeMusicAll_3->setVisible(true);
    ui.treeMusicAll->setVisible(true);
    ui.treeMusicAll_2->setVisible(true);

    }

void QZeroConfSharingUi::PopulateContactSpecificData()
    {
    
    TPtrC ptrName(reinterpret_cast<const TText*>(iSelectedContact.constData()));
    RBuf8 iname,mname,vname,fname;            
        RBuf8 contactName;
        contactName.Create(ptrName.Length());
        contactName.Copy(ptrName);
        //Find if its an already existing contact
#ifdef __arm
        CContactInfo* contact = GetSelectedContact(contactName);
        if(contact!=NULL)
#endif
          {
             //invoke the parser
#ifdef __arm
             fname.CreateL(contact->FileListPath(_L8("filelist.txt")));
             
             iname.CreateL(contact->ImgFileName());
             mname.CreateL(contact->MusicFileName());
             vname.CreateL(contact->VideoFileName());

#else
             _LIT8(KFileListName,"c:\\data\\filelist.txt");
             fname.CreateL(KFileListName);
             _LIT8(KFileImgName,"c:\\data\\ImgList.txt");
             iname.CreateL(KFileImgName);
             _LIT8(KFileMusicName,"c:\\data\\MusicList.txt");
             mname.CreateL(KFileMusicName);
             _LIT8(KFileVideoName,"c:\\data\\VideoList.txt");
             vname.CreateL(KFileVideoName);

#endif
             RBuf allfilenames;
             RBuf photofile;
             RBuf musicfile;
             RBuf videofile;
             
             allfilenames.CreateL(KMaxLength);
             photofile.CreateL(KMaxLength);
             musicfile.CreateL(KMaxLength);
             videofile.CreateL(KMaxLength);
                          
             allfilenames.Copy(fname);
             photofile.Copy(iname);
             musicfile.Copy(mname);
             videofile.Copy(vname);

             CFileParser* parser = CFileParser::NewL();
             parser->ParseFile(allfilenames,photofile,musicfile,videofile); 
             delete parser;
            
             allfilenames.Close();
             photofile.Close();
             musicfile.Close();
             videofile.Close();
          }
        contactName.Close();
        
    _LIT8(KPhoto,"c:\\data\\photolist.txt");
    _LIT8(KMusic,"c:\\data\\musiclist.txt");
    _LIT8(KVideo,"c:\\data\\videolist.txt");
    
    ////////////////////////////////////////////////////////////////////////////////////
    //first open the photo file & read it
    
    ui.treeContactMusic_2->clear();
    ui.treeContactMusic->clear();
    ui.treeContactMusic_3->clear();
    
    QString photofile = QString::fromUtf8((const char*)iname.Ptr(),iname.Length()); 
    iGenericFile.setFileName(photofile);
    iGenericFile.open(QIODevice::ReadOnly | QIODevice::Text);
    
    int count = 0;
    while(!iGenericFile.atEnd())
        {
            ReadFile();
            if(!filename.isEmpty())
                {
                new QTreeWidgetItem(ui.treeContactMusic_2);
                QTreeWidgetItem *qtreewidgetitem = ui.treeContactMusic_2->topLevelItem(count);
                qtreewidgetitem->setText(0,filename);
                count++;
                }
        }
    iGenericFile.close();
    ////////////////////////////////////////////////////////////////////////////////////////
    
    //now open music file & read it
    QString musicfile = QString::fromUtf8((const char*)mname.Ptr(),mname.Length()); 
    iGenericFile.setFileName(musicfile);
    iGenericFile.open(QIODevice::ReadOnly | QIODevice::Text);
    count = 0;
    while(!iGenericFile.atEnd())
        {
            ReadFile();
            if(!filename.isEmpty())
                {
                new QTreeWidgetItem(ui.treeContactMusic);
                QTreeWidgetItem *qtreewidgetitem = ui.treeContactMusic->topLevelItem(count);
                qtreewidgetitem->setText(0,filename);
                count++;
                }
        }
    iGenericFile.close();
            
    ////////////////////////////////////////////////////////////////////////////////////////
    //now open video file & read it
    
    QString videofile = QString::fromUtf8((const char*)vname.Ptr(),vname.Length()); 
    iGenericFile.setFileName(videofile);
    iGenericFile.open(QIODevice::ReadOnly | QIODevice::Text);
    count = 0;
    while(!iGenericFile.atEnd())
        {
            ReadFile();
            if(!filename.isEmpty())
                {
                new QTreeWidgetItem(ui.treeContactMusic_3);
                QTreeWidgetItem *qtreewidgetitem = ui.treeContactMusic_3->topLevelItem(count);
                qtreewidgetitem->setText(0,filename);
                count++;
                }
        }
    iGenericFile.close();
    ////////////////////////////////////////////////////////////////////////////
    //close all rbufs
    fname.Close();
    iname.Close();
    mname.Close();
    vname.Close();

    }

void QZeroConfSharingUi::ReadFile()
    {
    qint64 value = Q_INT64_C(255);    
    QByteArray str = iGenericFile.readLine(value);
    if((!str.isEmpty()) && (str.endsWith('\n')))
        str.remove((str.length()-1), 1);
    int index = str.lastIndexOf('/');
            //cut from the index posn
    filename = str.mid(index+1);      
    }

CContactInfo* QZeroConfSharingUi::GetSelectedContact(const TDesC8& aConatactName)
    {
    for(TInt i=0;i<iEntries.Count();i++)
       {
       if(iEntries[i]->ContactName().Compare(aConatactName)==0)                                                     
           {
           return iEntries[i];
           }
       }
    return NULL;
    }


void QZeroConfSharingUi::RequestSharedContent()
    {
    
    TPtrC ptrName(reinterpret_cast<const TText*>(iSelectedContact.constData()));
    RBuf8 contactName;
    contactName.Create(ptrName.Length());
    contactName.Copy(ptrName);
    
    //Find if its an already existing contact
    CContactInfo* contact = GetSelectedContact(contactName);
    if(contact!=NULL)
        {
        RBuf8 fileUrl;
        _LIT8(KFileList,"filelist.txt");
        fileUrl.Create(contact->FileUrl(KFileList));
        
        iSelectedFileListName = QString::fromUtf8((const char*)(contact->FileListPath(KFileList)).Ptr(),(contact->FileListPath(KFileList)).Length());
        
        QString qurl = QString::fromUtf8((const char*)(fileUrl).Ptr(),(fileUrl).Length());
        
        //QMessageBox::warning(this, tr("Icon Path"),qurl,QMessageBox::Ok);
    
        progressBar = new QProgressDialog(tr("Retrieving Shared Content"), tr("Cancel"), 0, 0);
        connect(progressBar, SIGNAL(canceled()), this, SLOT(ProgressBarCanceled()));
        progressBar->show();
    
#ifdef __arm 
        reply = manager->get(QNetworkRequest(QUrl(qurl)));
#else
        reply = manager->get(QNetworkRequest(QUrl("http://kiranp747.googlepages.com/FileList.txt")));
#endif
    
        connect(reply, SIGNAL(finished()), this, SLOT(RequestFinished()));
    
        fileUrl.Close();
        }
    contactName.Close();

    }
void QZeroConfSharingUi::on_listAvatars_itemClicked(QListWidgetItem* item)
{
    
    if(progressBar != NULL)
        return;

    iSelectedContact = item->text();
    
    setWindowTitle(iSelectedContact);
    ui.tabWidget->removeTab(0);
    ui.tabWidget->insertTab(0, ui.tabVivek, QIcon(":/Images/Unknown"), "Wall");
    ui.tabWidget->insertTab(4, ui.tabChat, QIcon(":/Icons/Chat"), "Chat");
    ui.tabWidget->setCurrentIndex(0);

    ShowBackButtons(true);
    
    ui.treeContactMusic->setVisible(true);
    ui.treeContactMusic_2->setVisible(true);
    ui.treeContactMusic_3->setVisible(true);

    ui.treeMusicAll_3->setVisible(false);
    ui.treeMusicAll->setVisible(false);
    ui.treeMusicAll_2->setVisible(false);
#ifndef __arm 
    PopulateContactSpecificData();
#endif
    
    RequestSharedContent();
    ShowCur_Status_and_Track();
    
}

void QZeroConfSharingUi::ProgressBarCanceled()
    {
    //if(progressBar && progressBar->isVisible())
    if(progressBar)
        {
        //progressBar->close();
        delete progressBar;
        progressBar = NULL;
        }
    }

void QZeroConfSharingUi::ItemRequestFinished()
    {
    if(progressBar && progressBar->isVisible())
        {
        progressBar->close();
        delete progressBar;
        progressBar = NULL;
        }

    int error = itemReply->error();
    if(!error)
        {
        QNetworkReply *reply = ((QNetworkReply *)sender());
        QByteArray data = reply->readAll();
        
        if(data.isEmpty())
            QMessageBox::warning(this, tr("Test"),tr("No Data Reply"),QMessageBox::Ok);
        
        QFile temp(iSelectedFileName);
        temp.open(QIODevice::WriteOnly | QIODevice::Truncate);
        temp.write(data);        
        temp.close();

        QUrl itemUrl(iSelectedFileName);
        
        bool ret = QDesktopServices::openUrl(itemUrl);
        if(!ret)
            QMessageBox::warning( this, tr("Operation Failed"), tr("Unkown error!"), QMessageBox::Close);

        }
    else
        QMessageBox::warning(this, tr("Test"),reply->errorString(),QMessageBox::Ok);

    

    }

void QZeroConfSharingUi::RequestFinished()
    {
    
    if(progressBar && progressBar->isVisible())
        {
        progressBar->close();
        delete progressBar;
        progressBar = NULL;
        }

    int error = reply->error();
    if(!error)
        {
        QNetworkReply *reply = ((QNetworkReply *)sender());
        QByteArray data = reply->readAll();
        
        if(data.isEmpty())
            QMessageBox::warning(this, tr("Test"),tr("No Data Reply"),QMessageBox::Ok);
        
        QFile temp(iSelectedFileListName);
        temp.open(QIODevice::WriteOnly | QIODevice::Truncate);
        temp.write(data);        
        temp.close();
        
        PopulateContactSpecificData();
            //}
        }
    else
        QMessageBox::warning(this, tr("Test"),reply->errorString(),QMessageBox::Ok);

    
    }

void QZeroConfSharingUi::ShowCur_Status_and_Track()
    {
    
    TPtrC ptrName(reinterpret_cast<const TText*>(iSelectedContact.constData()));
    
    RBuf8 contactName;
    RBuf8 currentTrack,currentUserStatus;
    
    contactName.Create(ptrName.Length());
    contactName.Copy(ptrName);
    
    //get complete contact info of the person
    
    for(TInt i=0;i<iEntries.Count();i++)
        {
        if(iEntries[i]->ContactName().Compare(contactName)==0)                                                     
                {     
                     currentTrack.CreateL(iEntries[i]->CurrentlyPlaying().Length());
                     currentTrack.Copy(iEntries[i]->CurrentlyPlaying());  
                     
                     currentUserStatus.CreateL(iEntries[i]->Status().Length());
                     currentUserStatus.Copy(iEntries[i]->Status());
                     
                     ui.textEdit_2->clear ();
                     QString nowPlayingLabel = "Now Playing: ";
                     QString nowPlayingTrack = QString::fromUtf8((const char*)currentTrack.Ptr(),currentTrack.Length());
                     QString total(nowPlayingLabel);
                     total.append(nowPlayingTrack);
                     
                     QString newline(tr("\n\n\n"));
                     total.append(newline);
                     QString nowStatusLabel = "Status: ";
                     total.append(nowStatusLabel);
                     QString nowStatusString = QString::fromUtf8((const char*)currentUserStatus.Ptr(),currentUserStatus.Length());
                     total.append(nowStatusString);            
                     
                                   
                     ui.textEdit_2->setText(total);                        
                }
         }
    currentTrack.Close();
    currentUserStatus.Close();
    contactName.Close(); 
     
    
    }//end of function


void QZeroConfSharingUi::ShowAllContacts(bool aShow)
{
    if(aShow)
    {
        // Contact Tab
        ui.tabWidget->removeTab(0);
        // Add All Contacts tab
        ui.tabWidget->insertTab(0, ui.tabContacts, QIcon(":/Icons/Contact"), "Contacts");
        // Chat Tab
        ui.tabWidget->removeTab(4);
        // Set Focus
        ui.tabWidget->setCurrentIndex(0);
    }
    else
    {
        ui.tabWidget->removeTab(0);
        //ui.tabWidget->insertTab(0, ui.tabVivek, QIcon(":/Images/Vivek"), "Vivek's Wall");
        ui.tabWidget->insertTab(4, ui.tabChat, QIcon(":/Icons/Chat"), "Chat");
        ui.tabWidget->setCurrentIndex(0);
    }
    // Music
    //ui.textMusicAll->setVisible(aShow);
    //ui.treeMusicAll->setVisible(aShow);
    //ui.treeContactMusic->setVisible(!aShow);

    ShowBackButtons(!aShow);
}

void QZeroConfSharingUi::ShowBackButtons(bool aShow)
{
    
    // Push Buttons
    ui.pushBackChat->setVisible(aShow);
    ui.pushBackContact->setVisible(aShow);
    ui.pushBackPhoto->setVisible(aShow);
    ui.pushBackMusic->setVisible(aShow);
    ui.pushBackVideo->setVisible(aShow);
    
    
}

void QZeroConfSharingUi::on_pushBackContact_clicked()
{
    ShowAllContacts(true);
}

void QZeroConfSharingUi::on_pushBackMusic_clicked()
{
    ShowAllContacts(true);
}

void QZeroConfSharingUi::on_pushBackVideo_clicked()
{
    ShowAllContacts(true);
}

void QZeroConfSharingUi::on_pushBackChat_clicked()
{
    ShowAllContacts(true);
}

void QZeroConfSharingUi::on_pushBackFile_clicked()
{
    ShowAllContacts(true);
}


void QZeroConfSharingUi::StartServer()
    {
    menuBar()->removeAction(shareAction);
    menuBar()->addAction(unshareAction);

    iHttpServer = CHttpServer::NewL();
    
    iHttpServer->ProcessSelectionL(EStart);
    
    CFileListEngine* filelister = CFileListEngine::NewL();
    filelister->SetOutputFileName(_L("c:\\data\\Images\\filelist.txt"));
    filelister->GetAllMediaContent();
    delete filelister;
    
    _LIT8(Kfilelist,"filelist.txt");
    _LIT8(KIconName,"mypic.ico");   
    iPublishBaseUrl.Create(KMaxPath);
    iPublishBaseUrl.Copy(_L8("http://"));
    iPublishBaseUrl.Append(iHttpServer->GetIPAddress());   
    iPublishBaseUrl.Append(_L8("/Images/")); //http://<ipaddr>/
   
    PublishMyService(Kfilelist,KIconName);    
    
    }


void QZeroConfSharingUi::StopServer()
    {
    //ToDo: Should stop server and unpublish the services.

    menuBar()->removeAction(unshareAction);
    menuBar()->addAction(shareAction);

    iZeroConfClient->UnPublishServices();
    iHttpServer->ProcessSelectionL(EStop); 
    delete iHttpServer;
    
    }

void QZeroConfSharingUi::NowPlaying(TDes& aTitleBuf)
    {
    //QString qtTitle = QString::fromUtf16(aTitleBuf.Ptr(),aTitleBuf.Length());
    //QMessageBox::warning(this,tr("Now playing"),qtTitle,QMessageBox::Ok);
    if(iUpdate)
        {
        iZeroConfClient->UpdateNowPlayingServiceL(aTitleBuf);
        }
    else
        {
        iZeroConfClient->PublishNowPlayingServiceL(aTitleBuf);
        iUpdate = ETrue;
        }
    }

void QZeroConfSharingUi::DiscoverServices()
    {

    iZeroConfClient->WriteServices();
    } 

void QZeroConfSharingUi::GetSrvInfo(const TDesC8& aQueryString,TDnsType aType)
    {
    iZeroConfClient->GetService(aQueryString,aType);
    }

void QZeroConfSharingUi::PublishService()
    {
    iZeroConfClient->PublishService();
    }

void QZeroConfSharingUi:: PublishMyService(const TDesC8& afilelist,const TDesC8& aIconName)
    {
    iZeroConfClient->PublishMyService(iPublishBaseUrl, afilelist, aIconName);
    }

QZeroConfSharingUi::~QZeroConfSharingUi()
    {
    iPublishBaseUrl.Close();
    
    iBaseUrl.Close();
    iIconName.Close();
    iFileName.Close();
    iCurrentlyPlaying.Close();
    iStatus.Close();
    iContactName.Close();
	MyStatusFile.close();
	
	for(TInt i=0;i<iEntries.Count();i++)
	        {
                delete iEntries[i];
	        }
	
	iEntries.Reset();        
    delete iNewContact;
    delete iNewContact;
    if(manager)
        {
        manager->disconnect();    
        delete manager;
        manager = 0;
        }
    }

void QZeroConfSharingUi::PopulateMainWindow(QString qname)
    {
    QTreeWidgetItem *qtreewidgetitem1 = new QTreeWidgetItem(ui.treeMusicAll_3);
    qtreewidgetitem1->setText(0,qname);
    ui.treeMusicAll_3->addTopLevelItem(qtreewidgetitem1);
    
    QTreeWidgetItem *qtreewidgetitem2 = new QTreeWidgetItem(ui.treeMusicAll);
    qtreewidgetitem2->setText(0,qname);
    ui.treeMusicAll->addTopLevelItem(qtreewidgetitem2);
    
    QTreeWidgetItem *qtreewidgetitem3 = new QTreeWidgetItem(ui.treeMusicAll_2);
    qtreewidgetitem3->setText(0,qname);
    ui.treeMusicAll_2->addTopLevelItem(qtreewidgetitem3);
    }
void QZeroConfSharingUi::OnPnPEventL (RPnPParameterBundleBase& aServiceEventInfo)
    {   
    //isPresent =EFalse;
    Log("ZeroConfSharingUi::OnPnPEventL - Entry\n");
    RBuf8 ptrInfo;
    aServiceEventInfo.Store(ptrInfo);   
    CContactInfo* contactInfo = NULL;
    TInt familyCount = aServiceEventInfo.CountParameterFamilies();
    for(TInt idx=0; idx<aServiceEventInfo.CountParameterFamilies();idx++)
        {
        RParameterFamily pnpFamily = aServiceEventInfo.GetFamilyAtIndex(idx);
        switch(pnpFamily.Id())
            {
            case EMdnsPtrParamset:
                {                 
                TUint count = pnpFamily.CountParameterSets ( RParameterFamily::ERequested ) ;
                for (TInt index= 0; index < count ; index++ )
                     {
                    CMDnsPtrParamSet* ptrParamSet = static_cast<CMDnsPtrParamSet*>(pnpFamily.GetParameterSetAtIndex( index, RParameterFamily::ERequested ));
                    RBuf name;
                    RBuf domain;
                    name.CreateL(255);
                    domain.CreateL(255);
                    name.Copy(ptrParamSet->InstanceName());
                    domain.Copy(ptrParamSet->DomainName()); 
    
                    _LIT(KServicesDns,"_services._dns-sd._udp.local.");
                    if(name.Compare(KServicesDns)!=0)
                        {
                        TChar ch = '.';
                        TInt pos = domain.Locate(ch);
    
                        if(pos != KErrNotFound)
                            {
                            RBuf buf16;
                            buf16.CreateL(domain.Mid(0,pos));
                            iSrvName.Close();
                            iSrvName.CreateL(buf16.Length());
                            iSrvName.Copy(buf16.Collapse());
                            //Dont query if you have got all records at a shot!!
                            if(aServiceEventInfo.CountParameterFamilies() <= 1)
                                {
                                Log("ZeroConfSharingUi::OnPnPEventL - Query for SRV\n");
                                QString tempname5 = QString::fromUtf8((const char*)iSrvName.Ptr(),iSrvName.Length());
                                                               
                               logFile.open(QIODevice::Append);
                               logFile.write(tempname5.toUtf8());        
                               logFile.close();
                                
                                GetSrvInfo(iSrvName,EDnsQType_Any);
                                }
                            buf16.Close();
                            }
                        }
                    
                    name.Close();
                    domain.Close();
                     }
                }
                break;
                
            case EMdnsSrvParamset:
                {
                TUint count = pnpFamily.CountParameterSets ( RParameterFamily::ERequested ) ;
                for (TInt index= 0; index < count ; index++ )
                     {
                    TBool isPresent = EFalse;
                    CMDnsSrvParamSet* srvParamSet = static_cast<CMDnsSrvParamSet*>(pnpFamily.GetParameterSetAtIndex( index, RParameterFamily::ERequested ));
                    RBuf name;
                    RBuf target;
                    name.CreateL(255);
                    target.CreateL(255);
                    target.Copy(srvParamSet->Target());
                    name.Copy(srvParamSet->DomainName());
                    
                    Log("ZeroConfSharingUi::OnPnPEventL - Print srv inst name\n\t");
                    QString tempname1 = QString::fromUtf16(name.Ptr(),name.Length());
                                                   
                   logFile.open(QIODevice::Append);
                   logFile.write(tempname1.toAscii());        
                   logFile.close();
    
                   Log("ZeroConfSharingUi::OnPnPEventL - Print target\n\t");
                   QString tempname2 = QString::fromUtf16(target.Ptr(),target.Length());
                                                                      
                  logFile.open(QIODevice::Append);
                  logFile.write(tempname2.toAscii());        
                  logFile.close();
                    TChar ch = '.';
                    TInt pos = target.Locate(ch);
                    
                    RBuf targetName;
                    targetName.CreateL(target.Mid(0,pos));
                    
                    if(iContactName.Length()!=0)
                        {
                        iContactName.Close();
                        }
                    iContactName.Create(targetName.Length());
                    iContactName.Copy(targetName);
                
                    for(TInt i=0;i<iEntries.Count();i++)
                        {
                        if(iEntries[i]->ContactName().Compare(iContactName)==0)                                                     
                                {   
                                Log("ZeroConfSharingUi::OnPnPEventL - Contact Exists\n\t");
                                
                                QString tempname = QString::fromUtf8((const char*)iContactName.Ptr(),iContactName.Length());
                                
                                logFile.open(QIODevice::Append);
                                logFile.write(tempname.toUtf8());        
                                logFile.close();

                                isPresent = ETrue;
                                break;                                              
                                }
                         }
                        if(!isPresent)
                            {
                            Log("ZeroConfSharingUi::OnPnPEventL - New Contact Added\n");
                            contactInfo = Create_Icon_Contact();
                            }
                        /*
                        if(aServiceEventInfo.CountParameterFamilies() <= 1)
                             {
                             GetSrvInfo(iSrvName,EDnsQType_Any);
                             }
                        */
                        name.Close();
                        target.Close();
                        targetName.Close();
                            
                        }
                    
                    
                     }
                break;
                
            case EMdnsTxtParamset:
                {
                TUint count = pnpFamily.CountParameterSets ( RParameterFamily::ERequested ) ;
                for (TInt index= 0; index < count ; index++ )
                     {
                     CMDnsTxtParamSet* txtParamSet = static_cast<CMDnsTxtParamSet*>(pnpFamily.GetParameterSetAtIndex( index, RParameterFamily::ERequested ));

                     RArray <RBuf8> txtData ;
                     txtParamSet->TxtDataL(txtData);
                      

                     if(contactInfo != NULL)
                         {
                         FetchBaseUrl(txtData);
                         FetchIconUrl(txtData);
                         FetchFileUrl(txtData);                      
                     
					 
                         contactInfo->SetBaseUrl(iBaseUrl);
                         FetchCurrentlyPlaying(txtData);
                         FetchStatus(txtData);
                         //See if we have got the Currently Played song
                         if(iCurrentlyPlaying.Length()!=0)
                             {
                         contactInfo->SetCurrentlyPlaying(iCurrentlyPlaying);
                           
                                 
                             }           
                         else if (iStatus.Length()!=0)
                             {
                         contactInfo->SetStatus(iStatus);
                             
                             }
                         iEntries.Append(Clone(contactInfo));
                       }  
                     else
                         {
                         FetchCurrentlyPlaying(txtData);     
                         FetchStatus(txtData);
                         CContactInfo** contact = NULL;
                         
                         for(TInt i=0;i<iEntries.Count();i++)
                             {
                             if(iEntries[i]->ContactName().Compare(iContactName)==0)                                                     
                                     { 
                                         if(iCurrentlyPlaying.Length()!=0)
                                             iEntries[i]->SetCurrentlyPlaying(iCurrentlyPlaying);
                                         else if(iStatus.Length()!=0)
                                             iEntries[i]->SetStatus(iStatus);
                                         
                                         TPtrC ptrName(reinterpret_cast<const TText*>(iSelectedContact.constData()));
                                         RBuf8 tempcontact;
                                         tempcontact.Create(ptrName.Length());
                                         tempcontact.Copy(ptrName);
                                         if(iEntries[i]->ContactName().Compare(tempcontact)== 0)
                                             {
                                                 ShowCur_Status_and_Track();
                                             }
                                         tempcontact.Close();
                                     }
                             }
                       
                        }
                     
                     }
                }
                break;
                
            case EMdnsPublishResponseParamset:
                {
                TUint count = pnpFamily.CountParameterSets ( RParameterFamily::ERequested ) ;
                for (TInt index= 0; index < count ; index++ )
                     {
                    CMDnsPublishResponseParamSet* publishRespParam = static_cast<CMDnsPublishResponseParamSet*>(pnpFamily.GetParameterSetAtIndex( index, RParameterFamily::ERequested ));
                    RBuf name;
                    name.CreateL(255);
                    name.Copy(publishRespParam->DomainName());             
                    _LIT(KCRLF, "\r\n A service was published with the name: \n");
                    RBuf str;
                    str.CreateL(255);
                    str.Copy(KCRLF);
                    name.Close();
                    str.Close();
                     }
                }
                break;
            }
        }
    ptrInfo.Close();
    Log("ZeroConfSharingUi::OnPnPEventL - Exit\n");
    }

void QZeroConfSharingUi::OnPnPError (TInt /*aError*/)
    {
        
    }


void QZeroConfSharingUi::FetchBaseUrl(RArray <RBuf8> aTxtData)
    {
    iBaseUrl.Close();
    
    _LIT8(KBaseUrl,"BaseUrl");
    TChar ch = '=';
    RBuf8 key;
    for(TInt index=0;index<aTxtData.Count();index++)
        {       
        TInt position = aTxtData[index].Locate(ch);
        if(position!= KErrNotFound)
            {
        key.Close();
        key.CreateL(aTxtData[index].Mid(0,(position-1)));
        if(key.Compare(KBaseUrl)==0)
            {
            iBaseUrl.CreateL(aTxtData[index].Mid((position+2)));           
            break;
            }        
            }
        }   
    key.Close();
    }

void QZeroConfSharingUi::FetchIconUrl(RArray <RBuf8> aTxtData)
    {
    iIconName.Close();
    
    _LIT8(KIconUrl,"IconUrl");
    TChar ch = '=';
    RBuf8 key;
    for(TInt index=0;index<aTxtData.Count();index++)
        {        
        TInt position = aTxtData[index].Locate(ch);
        if(position!= KErrNotFound)
            {
        key.Close();
        key.CreateL(aTxtData[index].Mid(0,(position-1)));
        if(key.Compare(KIconUrl)==0)
            {
            iIconName.CreateL(aTxtData[index].Mid((position+2)));
            break;
            }    
            }
        }
    key.Close();
    }

void QZeroConfSharingUi::FetchFileUrl(RArray <RBuf8> aTxtData)
    {
    iFileName.Close();
    
    _LIT8(KFileUrl,"FileUrl");
    TChar ch = '=';
    RBuf8 key;
    for(TInt index=0;index<aTxtData.Count();index++)
        {        
        TInt position = aTxtData[index].Locate(ch);
        if(position!= KErrNotFound)
            {
        key.Close();
        key.CreateL(aTxtData[index].Mid(0,(position-1)));
        if(key.Compare(KFileUrl)==0)
            {
            iFileName.CreateL(aTxtData[index].Mid((position+2)));
            break;
            }
            }
        }
    key.Close();
    }

void QZeroConfSharingUi::FetchCurrentlyPlaying(RArray <RBuf8> aTxtData)
    {
    iCurrentlyPlaying.Close();
    
    _LIT8(KNowPlaying,"Now playing");
    TChar ch = '=';
    RBuf8 key;
    TInt cnt = aTxtData.Count();
    for(TInt index=0;index<aTxtData.Count();index++)
        {        
        TInt position = aTxtData[index].Locate(ch);
        if(position!= KErrNotFound)
            {
        key.Close();
        key.CreateL(aTxtData[index].Mid(0,(position-1)));
        if(key.Compare(KNowPlaying)==0)
            {
            iCurrentlyPlaying.CreateL(aTxtData[index].Mid((position+2)));            
            break;
            }
            }
        }
    key.Close();
    }

void QZeroConfSharingUi::FetchStatus(RArray <RBuf8> aTxtData)
    {
    iStatus.Close();
    
    _LIT8(KStatus,"Status");
    TChar ch = '=';
    RBuf8 key;
    for(TInt index=0;index<aTxtData.Count();index++)
        {        
        TInt position = aTxtData[index].Locate(ch);
        if(position!= KErrNotFound)
            {
        key.Close();
        key.CreateL(aTxtData[index].Mid(0,(position-1)));
        if(key.Compare(KStatus)==0)
            {
            iStatus.CreateL(aTxtData[index].Mid((position+2)));            
            break;
            }
            }
        }
    key.Close();
    }


CContactInfo* QZeroConfSharingUi::Clone(CContactInfo* aContact)
    {
    //Clone the entry and insert in Hash
    CContactInfo* contact  = CContactInfo::NewL();    
    contact->SetBaseUrl(aContact->BaseUrl());
    contact->StoreContactDirectory(aContact->ContactDirectory());
    contact->SetContactName(aContact->ContactName());
    contact->SetCurrentlyPlaying(aContact->CurrentlyPlaying());
    contact->SetStatus(aContact->Status());
    
    return contact;
    
    //iContactEntries.Insert(contact->ContactName(),contact);
    }

CContactInfo* QZeroConfSharingUi::Create_Icon_Contact()
{
    CContactInfo* contact = NULL;
    QString qtName = QString::fromUtf8((const char*)iContactName.Ptr(),iContactName.Length());
    QString path(":/Icons/user");
    QListWidgetItem* item = new QListWidgetItem(QIcon(":/Images/Unknown"),qtName );
    ui.listAvatars->addItem(item);

    PopulateMainWindow(qtName);
    
   //Create a new contact
   contact = CContactInfo::NewL();
   contact->SetContactName(iContactName);
   //Creates the contact specific directory
   contact->SetContactDirectory();  
   
   return contact;
 
}
