/***************************************************************************
 *   Copyright (C) 2003 by Fred Schaettgen                                 *
 *   kdebluetooth@schaettgen.de                                            *
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/

#include "controller.h"
#include <qfile.h>
#include <kstandarddirs.h>
#include <krun.h>
#include <kdebug.h>
#include <stdlib.h>

Controller::Controller(QObject * parent) :
    QObject(parent)
{
    controllerInfo.name = "";
    controllerInfo.active = true;
    controllerInfo.fileExts = "";
    controllerInfo.pathToApp = "";
    controllerInfo.playlistMgr="Application";
    initialCommand = true;
}

QString Controller::name()
{
    return controllerInfo.name;
}

QString Controller::fileExts()
{
    return controllerInfo.fileExts;
}

QString Controller::pathToApp()
{
    return controllerInfo.pathToApp;
}

QString Controller::playlistManager()
{
    return controllerInfo.playlistMgr;
}

bool Controller::isActive()
{
    return (controllerInfo.active);
}

void Controller::setActive(bool a)
{
    controllerInfo.active=a;
}

QString Controller::launchApp()
{
    QString pathtoapp = pathToApp();
    int space = pathtoapp.find(" ");
    QString parms = "";
    if(space >= 0) {
        parms = pathtoapp.mid(space);
        if(!parms.isEmpty())
            parms = " " + parms;
    } else {
        space = pathtoapp.length();
    }
    QString appname = pathtoapp.mid(0, space);
    QString path_exe = KGlobal::dirs()->findExe(appname, getenv("PATH"));

    if(!path_exe.isEmpty()) {
        KRun::runCommand(path_exe + " " + parms);
    }
    return path_exe;
}

void Controller::loadPlaylist()
{
    QString playlistFile = locateLocal("appdata", controllerInfo.name + "-controller.m3u");
    if(QFile::exists(playlistFile)) {
        commandRMAL();
        commandLADD(playlistFile);
    } // else leave whatever controller may have auto-loaded
}

void Controller::savePlaylist()
{
    QString playlistFile = locateLocal("appdata", controllerInfo.name + "-controller.m3u");
    int curPos;
    QStringList playlist = commandPLST(curPos, true);

    if(playlist.count() > 0 ) {
        QFile f(playlistFile);
        if(f.open( IO_WriteOnly )) {
            QTextStream stream( &f );
            for ( QStringList::Iterator it = playlist.begin(); it != playlist.end(); ++it )
                stream << *it << "\n";
            f.close();
       }
    }
}

Controller::~Controller()
{
}


#include "controller.moc"
