/***************************************************************************
 *   Copyright (C) 2005 - 2007 by                                          *
 *      Christian Muehlhaeuser, Last.fm Ltd <chris@last.fm>                *
 *      Erik Jaelevik, Last.fm Ltd <erik@last.fm>                          *
 *                                                                         *
 *   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 "lastfmapplication.h"
#include "breakpad/BreakPad.h"
#include "MooseCommon.h"
#include <QDebug>

// for Mac, see getURLEvent() below
static QString openUrl;


bool
isAlreadyRunning()
{
  #ifdef WIN32
    QString id( "Lastfm-F396D8C8-9595-4f48-A319-48DCB827AD8F" );
    ::CreateMutexA( NULL, false, id.toAscii() );

    // The call fails with ERROR_ACCESS_DENIED if the Mutex was 
    // created in a different users session because of passing
    // NULL for the SECURITY_ATTRIBUTES on Mutex creation);
    return ::GetLastError() == ERROR_ALREADY_EXISTS || ::GetLastError() == ERROR_ACCESS_DENIED;
  #else
    return LastFmApplication::sendToInstance();
  #endif
}


/******************************************************************************
    getURLEvent (Apple's way to tell us about cli-args)
******************************************************************************/

#ifdef Q_WS_MAC
#include <ApplicationServices/ApplicationServices.h>

static pascal OSErr
getURLEvent( const AppleEvent* appEvent, AppleEvent* /*reply*/, long /*handlerRefcon*/ )
{
    qDebug() << "Receiving apple url event";

    DescType type;
    Size size;

    char buf[1024];
    AEGetParamPtr( appEvent, keyDirectObject, typeChar, &type, &buf, 1023, &size );
    buf[size] = '\0';

    openUrl = QString::fromUtf8( buf );

    // Send to currently running instance, otherwise variable openUrl
    // will be picked up by the main function
    if ( isAlreadyRunning() )
        LastFmApplication::sendToInstance( openUrl );

    return noErr;
}


static pascal OSErr
getOpenEvent( const AppleEvent* /*appEvent*/, AppleEvent* /*reply*/, long /*handlerRefcon*/ )
{
    qDebug() << "Receiving apple open event";

    if ( isAlreadyRunning() )
        LastFmApplication::sendToInstance( "container://show" );

    return noErr;
}

#endif //Q_WS_MAC


/******************************************************************************
    main
******************************************************************************/
int main( int argc, char *argv[] )
{
    #ifndef NBREAKPAD
    BreakPad breakpad( MooseUtils::savePath() );
    breakpad.setProductName( "Last.fm Client" );
    #endif

    // used by some Qt stuff, eg QSettings
    // leave first! As Settings object is created quickly
    QCoreApplication::setApplicationName( "Last.fm" );
    QCoreApplication::setOrganizationName( "Last.fm" );
    QCoreApplication::setOrganizationDomain( "last.fm" );

    #ifdef Q_WS_MAC
    AEInstallEventHandler( 'GURL', 'GURL', NewAEEventHandlerUPP( getURLEvent ), 0, false );
    AEInstallEventHandler( kCoreEventClass, kAEReopenApplication, NewAEEventHandlerUPP( getOpenEvent ), 0, false );
    #endif

    // Check for commandline parameters
    // we support one URL passed, only one. If there is more we use the last one
    bool openToTray = false;
    for ( int i = 1; i < argc; i++ )
    {
        QString const arg = argv[i];

        if ( arg.startsWith( "lastfm://" ) || arg.startsWith( "container://" ) )
            openUrl = QString( argv[i] );

        if ( arg == "-tray" || arg == "--tray" )
            openToTray = true;
    }

    #ifndef LASTFM_MULTI_PROCESS_HACK
        if ( isAlreadyRunning() )
        {
            if ( !openToTray )
                LastFmApplication::sendToInstance( "container://show" );

            if ( !openUrl.isEmpty() )
                LastFmApplication::sendToInstance( openUrl );

            //FIXME shouldn't we return 0? Since we exit successfully?
            // though it could be that some other code depends on this return code
            // so I'm not changing anything, if you know better fix this! --mxcl
            return 1;
        }
    #endif

    #ifdef Q_WS_MAC
        // on mac we do this because mac arguments with urls are handled wierdly
        // ask muesli/chris as he is our expert on this matter
        if ( !openUrl.isEmpty() )
        {
            argc++;
            char** argv_cp = new char*[argc];
            for ( int i = 0; i < argc - 1; ++i )
                argv_cp[i] = argv[i];

            argv_cp[argc - 1] = openUrl.toLocal8Bit().data();
            argv = argv_cp;
        }
    #endif

    LastFmApplication app( argc, argv );
    return app.exec();
}
