/*
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <qapplication.h>
#include <qcheckbox.h>
#include <qdir.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qmessagebox.h>
#include <qstring.h>

#include "Playlist.h"
#include "PlaylistCheck.h"
#include "PlaylistDialog.h"
#include "PlaylistEditDialog.h"
#include "PlaylistUpdateDialog.h"
#include "wrapper/SongLength.h"
#include "wrapper/SidTuneWrapper.h"

bool PlaylistCheck::checkBaseDir(QWidget* parent, Playlist* playlist,
                                 const QFileDialog* fileDlg)
{
    if ( playlist->baseDir.isEmpty() )
        return true;

    // Deal with that stupid 'baseDir' path prefix.
    // Query the user to enter a valid baseDir as long as
    // the first file cannot be found.
    do
    {
        QString testFileName = playlist->baseDir + playlist->list.at(0)->fileNameString;
        QFile testFile(testFileName);
        if ( testFile.exists() )  // baseDir seems to be good
            break;
        else
        {
            QString tmp = "Could not find first file from playlist:\n\n";
            tmp += testFileName;
            tmp += "\n\n"
                   "You may adjust the playlist's base sidtunes\n"
                   "directory now or cancel.";
            QMessageBox error;
            error.setIcon(QMessageBox::Critical);
            error.setText(tmp);
            error.adjustSize();
            error.exec();
            
            QString dirName = 
                QFileDialog::getExistingDirectory(fileDlg->dirPath(),parent,0,
                                                  "Open sidtunes base directory");
            if ( dirName.isEmpty() )
            {
                // User cancelled. Do not accept the given list.
                return false;
            }
            else
            {
                // Strip trailing slash.
                if (dirName.length() && dirName[dirName.length()-1]==QDir::separator() )
                    dirName.remove(dirName.length()-1,1);
                playlist->baseDir = dirName;
                playlist->setModified();
            }
        }
    }
    while ( true );
    
    QApplication::setOverrideCursor( Qt::waitCursor );
    playlist->removeBaseDir();
    if ( playlist->getFormat()==1 )
        playlist->fixMissingInfo();
    QApplication::restoreOverrideCursor();
    
    return true;
}

void PlaylistCheck::updateEntries(QWidget* parent, Playlist* playlist,
                                  PlaylistDialog* playlistDlg,
                                  PlaylistEditDialog* playlistEditDlg,
                                  const QFileDialog* fileDlg)
{
    bool updatePlaytime = false;
    bool updateStartsong = false;
        
    PlaylistUpdateDialog* myDlg = new PlaylistUpdateDialog(parent,"Playlist Update Dialog",true);
    myDlg->playtimeCheckBox->setChecked( false );
    myDlg->startsongCheckBox->setChecked( false );
    myDlg->playtimeCheckBox->setDisabled( !SongLength::isAvailable() );
    int result = myDlg->exec();
    if ( result==QDialog::Accepted )
    {
        updatePlaytime = myDlg->playtimeCheckBox->isChecked();
        updateStartsong = myDlg->startsongCheckBox->isChecked();
    }
    delete myDlg;
    if ( result==QDialog::Rejected )
        return;
    // Traverse a complete playlist and update the sidtune credits,
    // number of sids, and also give the user a chance to correct
    // the file name of sids that may have moved meanwhile.
    QApplication::setOverrideCursor( Qt::waitCursor );
    SidTuneWrapper* mySidLoader = new SidTuneWrapper;  // unchecked alloc
    playlist->lock();
    QListIterator<PlaylistItem> it(playlist->list);
    bool ignoreAll = false;
    for ( it.toFirst(); it.current(); ++it ) 
    {
        PlaylistItem* item = it.current();
        if ( mySidLoader->open(item->fileNameString) )
        {
            // Check whether sid info in file is different.
            if ( item->titleString!=mySidLoader->getInfoString(0) ||
                item->authorString!=mySidLoader->getInfoString(1) ||
                item->copyrightString!=mySidLoader->getInfoString(2) || 
                item->songs!=mySidLoader->getSongs() )
            {
                playlist->setModified();
            }
            // Copy sid info from file.
            item->titleString = mySidLoader->getInfoString(0);
            item->authorString = mySidLoader->getInfoString(1);
            item->copyrightString = mySidLoader->getInfoString(2);
            item->songs = mySidLoader->getSongs();
            if ( updateStartsong )
            {
                if ( item->subtune != mySidLoader->getStartSong() )
                    playlist->setModified();
                item->subtune = mySidLoader->getStartSong();
            }
            // Make sure a changed sid does not mess up
            // the custom starting song.
            if ( item->subtune>item->songs || item->subtune==0 )
            {
                item->subtune = mySidLoader->getStartSong();
                playlist->setModified();
            }
            if ( updatePlaytime )
            {
                SongLengthDBitem sli;
                // If anything goes wrong here or this sidtune is not in the DB,
                // don't update the current playtime.
                if ( SongLength::getItem( item->fileNameString, item->subtune, sli )  )
                {
                    if ( item->time != sli.playtime )
                        playlist->setModified();
                    item->time = sli.playtime;
                }
            }
        }
        else if ( !ignoreAll ) // sidtune not found
        {
            QString tmp = "Could not load the following playlist entry:\n\n";
            tmp += item->fileNameString;
            if ( playlist->getFormat()!=1 )
            {
                tmp += "\n\n";
                if ( !item->titleString.isEmpty() )
                {
                    tmp += "    ";
                    tmp += item->titleString;
                    tmp += "\n";
                }
                if ( !item->authorString.isEmpty() )
                {
                    tmp += "    ";
                    tmp += item->authorString;
                    tmp += "\n";
                }
                if ( !item->copyrightString.isEmpty() )
                {
                    tmp += "    ";
                    tmp += item->copyrightString;
                    tmp += "\n";
                }
            }
            QMessageBox mb( "SIDPLAY",
                           tmp,
                           QMessageBox::Warning,
                           QMessageBox::Yes,
                           QMessageBox::Ignore | QMessageBox::Default | QMessageBox::Escape,
                           QMessageBox::Abort);
            mb.setButtonText( QMessageBox::Yes, "Browse" );
            mb.setButtonText( QMessageBox::Ignore, "Ignore" );
            mb.setButtonText( QMessageBox::Abort, "Ignore All" );
            QApplication::restoreOverrideCursor();
            int ret = mb.exec();
            if ( ret==QMessageBox::Abort )
                ignoreAll = true;
            else if ( ret==QMessageBox::Yes )
            {
                QString fileName = QFileDialog::getOpenFileName(fileDlg->dirPath(),
                                                                fileDlg->selectedFilter(),parent,0,"SIDPLAY: Select file");
                if ( !fileName.isEmpty() )
                {
                    if ( mySidLoader->open(fileName) )
                    {
                        // Copy sid info from file.
                        item->fileNameString = fileName;
                        item->titleString = mySidLoader->getInfoString(0);
                        item->authorString = mySidLoader->getInfoString(1);
                        item->copyrightString = mySidLoader->getInfoString(2);
                        item->songs = mySidLoader->getSongs();
                        // Make sure a changed sid does not mess up
                        // the custom starting song.
                        if ( item->subtune > item->songs )
                            item->subtune = mySidLoader->getStartSong();
                        playlist->setModified();
                    }
                }
            }
            QApplication::setOverrideCursor( Qt::waitCursor );
        }
    }
    playlist->unlock();
    delete mySidLoader;
    playlistDlg->takeList(playlist);
    playlistEditDlg->takeList(playlist);
    QApplication::restoreOverrideCursor();
}

