/***************************************************************************
 *   Copyright (C) 2004 by Marco Gulino                                    *
 *   marco@Paganini                                                        *
 *                                                                         *
 *   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 "universalamarok.h"
#include "amarokdcopiface_stub.h"


#include <tqlabel.h>
#include <tdeinstance.h>
#include <tdelocale.h>
#include <tqstring.h>
#include <tqwidget.h>
#include <tdeglobal.h>
#include <kstandarddirs.h>
#include <tqlayout.h>
#include <tqtimer.h>
#include <dcopclient.h>
#include <tdemessagebox.h>
#include <kpushbutton.h>
#include <kiconloader.h>
#include <tqdatetime.h>
#include <tqfileinfo.h>
#include <tdetoolbar.h>
#include <tdeapplication.h>
#include <tqslider.h>
#include <kdebug.h>
#include <kurldrag.h>
#include <tdehtmlview.h>

#define HTML_FILE TDEGlobal::dirs()->saveLocation( "data", "amarok/", true ) + "contextbrowser.html"

amarokWidget::amarokWidget( TQWidget * parent, const char * name, WFlags f )
                 : TQVBox(parent, name, f)
{
    setAcceptDrops(true);
}
void amarokWidget::dragEnterEvent(TQDragEnterEvent* event)
{
    event->accept( KURLDrag::canDecode(event) );
}

void amarokWidget::dropEvent(TQDropEvent* event)
{
    KURL::List urlList;
    if( KURLDrag::decode(event, urlList) )
    {
        KURL::List::iterator it;
        KURL::List::iterator end( urlList.end() );
        for (it = urlList.begin(); it != end; ++it )
            emit emitURL(*it);
    }
}

bool amarokWidget::eventFilter( TQObject *, TQEvent *e )
{
    if(e->type() < TQEvent::DragEnter || e->type() > TQEvent::Drop )
        return false;
    TQApplication::sendEvent(this, e);
    return true;
}

UniversalAmarok::UniversalAmarok(TDEInstance *inst,TQObject *parent,TQWidget *widgetParent, TQString &desktopName, const char* name):
                   KonqSidebarPlugin(inst,parent,widgetParent,desktopName,name)
{
    TDEGlobal::iconLoader()->addAppDir( "amarok" );
    widget = new amarokWidget( widgetParent );
//    widgetParent->resize(580,300);
    TDEToolBar *topBar = new TDEToolBar( widget, "Topbar" );
    topBar->setIconSize(16);
    topBar->insertButton( "today",    0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( currentTrack() ) );
    topBar->insertButton( "text-x-generic", 0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( lyrics() ) );
    topBar->insertButton( "preferences-desktop-personal", 0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( wiki() ) );

    browser = new TDEHTMLPart(widget, "widget-browser");
//browser=new TDEHTMLPart(widget);
    kdDebug() << "parentPart() << " << browser->parentPart() << endl;
    browser->setDNDEnabled( true );
    browser->setEncoding( "utf8", true );
    updateBrowser( HTML_FILE );
    browser->view()->installEventFilter( widget );
    amarokDCOP = new DCOPClient();
    amarokDCOP->attach();

    playerStub   = new AmarokPlayerInterface_stub( amarokDCOP, "amarok", "player");
    playlistStub = new AmarokPlaylistInterface_stub( amarokDCOP, "amarok", "playlist");
    contextStub = new AmarokContextBrowserInterface_stub (amarokDCOP, "amarok", "contextbrowser");

    TDEToolBar* toolBar=new TDEToolBar(widget, "PlayerControls");

    toolBar->setIconSize(16);
    toolBar->insertButton( "media-skip-backward",0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( sendPrev() ) );
    toolBar->insertButton( "media-playback-start", 0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( sendPlay() ) );
    toolBar->insertButton( "media-playback-pause",0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( sendPause() ) );
    toolBar->insertButton( "media-playback-stop", 0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( sendStop() ) );
    toolBar->insertButton( "media-skip-forward",  0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( sendNext() ) );

    toolBar->insertSeparator();
    toolBar->insertButton( "arts",        0, TQ_SIGNAL( clicked() ), this, TQ_SLOT( sendMute() ) );

    vol_slider = new TQSlider(0,100,1,0,TQt::Horizontal, toolBar,"volume");
    vol_slider->setLineStep(2);

    connect(vol_slider, TQ_SIGNAL( valueChanged(int) ), this, TQ_SLOT(volChanged(int ) ) );
    toolBar->insertWidget(1,2, vol_slider);

    fileInfo  = new TQFileInfo(HTML_FILE);
    TQTimer *t = new TQTimer( this );

    connect( t, TQ_SIGNAL(timeout()), TQ_SLOT(updateStatus() ) );
    t->start( 2000, false );
    kdDebug() << "Connecting widget signal" << endl;

    connect( widget,                      TQ_SIGNAL( emitURL( const KURL &)),
             this,                        TQ_SLOT( openURLRequest( const KURL &) ) );
    connect( browser->browserExtension(), TQ_SIGNAL( openURLRequest( const KURL &, const KParts::URLArgs & ) ),
             this,                        TQ_SLOT( openURLRequest( const KURL & ) ) );
    widget->show();
}


UniversalAmarok::~UniversalAmarok()
{
    delete fileInfo;
}


#include "universalamarok.moc"

// FIXME: is this referenced from anywhere ??!
extern "C"
{
    TDE_EXPORT void* create_konqsidebar_universalamarok(TDEInstance *instance,TQObject *par,TQWidget *widp,TQString &desktopname,const char *name)
    {
        TDEGlobal::locale()->insertCatalogue( "amarok" );
        return new UniversalAmarok(instance,par,widp,desktopname,name);
    }
}

// FIXME: Is this referenced from anywhere ??!
extern "C"
{
    TDE_EXPORT bool add_konqsidebar_universalamarok(TQString* fn, TQString* param, TQMap<TQString,TQString> *map)
        {
        Q_UNUSED(param);

        map->insert ("Type", "Link");
        map->insert ("URL", "");
        map->insert ("Icon", "amarok");
        map->insert ("Name", i18n ("Amarok"));
        map->insert ("Open", "true");
        map->insert ("X-TDE-KonqSidebarModule","konqsidebar_universalamarok");
        fn->setLatin1 ("amarok.desktop");
        return true;
    }
}


/*!
    \fn UniversalAmarok::updateBrowser()
 */
void UniversalAmarok::updateBrowser(const TQString& file)
{
    if (! (TQFile::exists(file) ) )
    {
        showIntroduction();
        return;
    }
    TQString text;
    TQFile f_file(file);
    if( f_file.open(IO_ReadOnly) )
    {
        TQTextStream stream( &f_file );
        stream.setEncoding( TQTextStream::UnicodeUTF8 );
        TQString line;
        while ( !stream.atEnd() ) {
            line = stream.readLine(); // line of text excluding '\n'
             text += TQString("\n") + line;
        } f_file.close();
            text=text.replace("<img id='current_box-largecover-image' ", "<img id='current_box-largecover-image' width=70 height=70 ");
        browser->begin();
        browser->write(text);
        browser->end();
    } else
    browser->openURL(file);
}


/*!
    \fn UniversalAmarok::updateStatus()
 */
void UniversalAmarok::updateStatus()
{
    checkForAmarok();
    vol_slider->setValue( playerStub->getVolume() );
    fileInfo->refresh();
    if( fileInfo->lastModified() != fileDT )
    {
        updateBrowser( HTML_FILE );
        fileDT=fileInfo->lastModified();
    }
}


/*!
    \fn UniversalAmarok::getCurrentPlaying()
 */
TQString UniversalAmarok::getCurrentPlaying()
{
    return playerStub->nowPlaying();
}


/*!
    \fn UniversalAmarok::openURLRequest( const KURL &url )
 */
void UniversalAmarok::openURLRequest( const KURL &url )
{
   if( ! url.isValid() ) return;
   if (url.url() == "run:amarok") {
        runAmarok();
        return;
   }
   checkForAmarok();
   playlistStub->playMedia(url);
}


/*!
    \fn UniversalAmarok::checkForAmarok()
 */
void UniversalAmarok::checkForAmarok()
{
    if(!amarokDCOP->isApplicationRegistered("amarok"))
        noAmarokRunning();
}


void UniversalAmarok::noAmarokRunning() {
    TQString  m_HTMLSource="";
    m_HTMLSource.append(
            "<html>"
            "<div id='introduction_box' class='box'>"
                "<div id='introduction_box-header' class='box-header'>"
                    "<span id='introduction_box-header-title' class='box-header-title'>"
                    + i18n( "Amarok is not running!" ) +
                    "</span>"
                "</div>"
                "<div id='introduction_box-body' class='box-body'>"
                    "<p>" +
                    i18n( "To run Amarok, just click on the link below: "
                        ) +
                    "</p>"
                    "<a href='run:amarok' class='button'>" + i18n( "Run Amarok..." ) + "</a>"
                "</div>"
            "</div>"
            "</html>"
                       );
    browser->begin();
    browser->write( m_HTMLSource );
    browser->end();
}

void UniversalAmarok::runAmarok() {
    TDEApplication::tdeinitExecWait("amarok");
}



void UniversalAmarok::volChanged(int vol)
{
    checkForAmarok();
    playerStub->setVolume(vol);
}

void UniversalAmarok::showIntroduction()
{
    TQString  m_HTMLSource="";
    m_HTMLSource.append(
            "<html>"
            "<div id='introduction_box' class='box'>"
                "<div id='introduction_box-header' class='box-header'>"
                    "<span id='introduction_box-header-title' class='box-header-title'>"
                    + i18n( "Hello Amarok user!" ) +
                    "</span>"
                "</div>"
                "<div id='introduction_box-body' class='box-body'>"
                    "<p>" +
                    i18n( "This is the Context Browser: "
                          "it shows you contextual information about the currently playing track. "
                          "In order to use this feature of Amarok, you need to build a Collection."
                        ) +
                    "</p>"
                    "<a href='show:collectionSetup' class='button'>" + i18n( "Build Collection..." ) + "</a>"
                "</div>"
            "</div>"
            "</html>"
                       );
kdDebug() << m_HTMLSource << endl;
    browser->begin();
    browser->write( m_HTMLSource );
    browser->end();
}
