/*****************************************************************

Copyright (c) 2000 the kicker authors. See file AUTHORS.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <time.h>
#include <qstringlist.h>
#include <qvaluelist.h>
#include <qregexp.h>

#include <kglobal.h>
#include <kdebug.h>
#include <kconfig.h>
#include <klocale.h>

#include "recentapps.h"

RecentlyLaunchedApps::RecentlyLaunchedApps()
{
    // set defaults
    m_bRecentVsOften = false;
    m_nNumVisible = 5; // max entries to display
    setAutoDelete( true );
    m_nNumMenuItems = 0;
    m_bNeedToUpdate = false;
    m_bInitialised = false;
}

int RecentlyLaunchedApps::compareItems( QPtrCollection::Item item1, QPtrCollection::Item item2 )
{
   // Sort items in descending order according to either last launch time or launch count.
   RecentlyLaunchedAppInfo* lhs = static_cast<RecentlyLaunchedAppInfo*>( item1 );
   RecentlyLaunchedAppInfo* rhs = static_cast<RecentlyLaunchedAppInfo*>( item2 );
   return m_bRecentVsOften
       ? rhs->getLastLaunchTime() - lhs->getLastLaunchTime()
       : rhs->getLaunchCount() - lhs->getLaunchCount();
}

void RecentlyLaunchedApps::init()
{
    if ( m_bInitialised )
       return;

    m_nNumMenuItems = 0;
    clear();

    configChanged();

    KConfig *config = KGlobal::config();
    config->setGroup("menus");
    QStringList recentApps = config->readListEntry("RecentAppsStat");

    for ( QStringList::ConstIterator it = recentApps.begin(); it != recentApps.end(); ++it )
    {
        QRegExp re( "(\\d*) (\\d*) (.*)" );
        if ( re.search(*it) != -1 )
        {
            int nCount = re.cap(1).toInt();
            long lTime = re.cap(2).toLong();
            QString szPath = re.cap(3);
            append( new RecentlyLaunchedAppInfo( szPath, nCount, time_t( lTime ) ) );
        }
    }

    sort();

    m_bInitialised = true;
}

void RecentlyLaunchedApps::configChanged()
{
    KConfig *config = KGlobal::config();
    config->setGroup("menus");

    m_nNumVisible = QMIN( config->readNumEntry( "NumVisibleEntries", m_nNumVisible ), 100 );
    m_bRecentVsOften = config->readBoolEntry( "RecentVsOften", m_bRecentVsOften );

    sort();
}

void RecentlyLaunchedApps::save()
{
    KConfig *config = KGlobal::config();
    config->setGroup("menus");

    QStringList recentApps;

    for ( QPtrListIterator<RecentlyLaunchedAppInfo> it( *this ); it.current(); ++it )
    {
        recentApps.append( QString("%1 %2 %3").arg( (*it)->getLaunchCount() )
                                              .arg( (*it)->getLastLaunchTime() )
                                              .arg( (*it)->getDesktopPath() ) );
    }

    config->writeEntry("RecentAppsStat", recentApps);
    config->sync();
}

void RecentlyLaunchedApps::appLaunched( const QString& strApp )
{
    for ( QPtrListIterator<RecentlyLaunchedAppInfo> it( *this ); it.current(); ++it )
    {
        if ( (*it)->getDesktopPath() == strApp )
        {
            (*it)->increaseLaunchCount();
            (*it)->setLastLaunchTime( time(0) );
            sort();
            return;
        }
    }

    inSort( new RecentlyLaunchedAppInfo( strApp, 1, time(0) ) );
}

void RecentlyLaunchedApps::getRecentApps( QStringList& recentApps )
{
    recentApps.clear();

    for ( QPtrListIterator<RecentlyLaunchedAppInfo> it( *this ); it.current() && recentApps.count() < m_nNumVisible; ++it )
    {
        recentApps.append( (*it)->getDesktopPath() );
    }
}

void RecentlyLaunchedApps::removeItem( const QString& strName )
{
    for ( QPtrListIterator<RecentlyLaunchedAppInfo> it( *this ); it.current(); ++it )
    {
        if ( (*it)->getDesktopPath() == strName )
        {
            removeRef(*it);
            return;
        }
    }
}

void RecentlyLaunchedApps::clearRecentApps()
{
    clear();
}

QString RecentlyLaunchedApps::caption() const
{
    return m_bRecentVsOften ? i18n("Recently Used Applications") : i18n("Most Used Applications");
}
