#include "cuesheeteditor.h"

#include <tqlayout.h>
#include <tqstring.h>

#include <tdelocale.h>
#include <kiconloader.h>
#include <kpushbutton.h>
#include <tdemessagebox.h>
//#include <ktextedit.h>

/*#include <tdeparts/factory.h> // KPart Factory
#include <klibloader.h>     // LibLoader, contains factories
#include <kate/document.h>  // Katepart document
#include <kate/view.h>      // Katepart view
*/

// ### soundkonverter 0.4: import/export flac cuesheet

CuesheetEditor::CuesheetEditor( TQWidget *parent, const char *name, bool modal, WFlags f )
    : KDialog( parent, name, modal, f )
{
    // TODO can the cuesheet editor be extendet by more tags (composer), etc.

    // create an icon loader object for loading icons
    TDEIconLoader* iconLoader = new TDEIconLoader();

    setCaption( i18n("Cuesheet Editor") );
    resize( 600, 400 );
    setIcon( iconLoader->loadIcon("kwrite",TDEIcon::Small) );

    TQGridLayout *grid = new TQGridLayout( this, 4, 1, 11, 6 );

    tTextEdit = new KTextEdit( this, "tTextEdit" );
    tTextEdit->setFocus();
    grid->addWidget( tTextEdit, 0, 0 );

/*
    // Get KPart factory for the katepart library.
    // This returns 0, if the library can not be found
    KParts::Factory* factory = (KParts::Factory *)
        KLibLoader::self()->factory ("libkatepart");

    if (factory)
    {
        // The library was found, so create the Kate::Document
        KTextEditor::Document *doc = (KTextEditor::Document *)
            factory->createPart( 0, "", this, "", "KTextEditor::Document" );

        // The document only represents the document, to view
        // the document's content
        // we have to create a view for the document.
        Kate::View *view = (Kate::View *) doc->createView( this, 0L );

        // all went well, so return the view
        //return view;
        grid->addWidget( view, 0, 0 );
    }
    else
    {
        // The library was not found
        //return 0L;
    }
*/

    TQHBoxLayout *buttonBox = new TQHBoxLayout();
    grid->addLayout( buttonBox, 3, 0 );

    pHelp = new KPushButton( iconLoader->loadIcon("help",TDEIcon::Small), "", this, "pHelp" );
    buttonBox->addWidget( pHelp );
    connect( pHelp, TQT_SIGNAL(clicked()),
               this, TQT_SLOT(help())
             );

    pGenerate = new KPushButton( iconLoader->loadIcon("document-new",TDEIcon::Small), i18n("Generate"), this, "pGenerate" );
    buttonBox->addWidget( pGenerate );
    connect( pGenerate, TQT_SIGNAL(clicked()),
               this, TQT_SLOT(generate())
             );

    pConvert = new KPushButton( iconLoader->loadIcon("system-run",TDEIcon::Small), i18n("Format"), this, "pConvert" );
    buttonBox->addWidget( pConvert );
    connect( pConvert, TQT_SIGNAL(clicked()),
               this, TQT_SLOT(convert())
             );

    pShift = new KPushButton( iconLoader->loadIcon("reload",TDEIcon::Small), i18n("Shift Title/Performer"), this, "pShift" );
    buttonBox->addWidget( pShift );
    connect( pShift, TQT_SIGNAL(clicked()),
               this, TQT_SLOT(shift())
             );

    buttonBox->addStretch();

    pOk = new KPushButton(iconLoader->loadIcon("system-log-out",TDEIcon::Small), i18n("Close"), this, "pOk" );
    pOk->setFocus();
    buttonBox->addWidget( pOk );
    connect( pOk, TQT_SIGNAL(clicked()),
               this, TQT_SLOT(accept())
             );

    // delete the icon loader object
    delete iconLoader;
}

CuesheetEditor::~CuesheetEditor()
{}

void CuesheetEditor::help()
{
    KMessageBox::information( this,
        i18n("<p>With this small tool you can process cue files as they are used for burning music mixes and for organizing them in media players like amaroK.<br><br>You can generate a new file by pasting text into the input area. It must be formated the following way:<br><br>Title - Artist [time]<br>Title - Artist [3:25]<br>Title - Artist [2:37]<br>...<br>A tip: Use kwrite and regular expressions to format it this way.</p>"),
        i18n("Cuesheet Editor - Help") );
}

void CuesheetEditor::generate()
{
    TQString text = tTextEdit->text();
    TQString newText;
    TQStringList titleList, performerList;
    TQValueList<int> timeList;
    TQString time;
    int min, sec;
    int index;

    while( index != -1 )
    {
        index = text.find( " - " );
        if( index == -1 )
            break;
        titleList.append( text.left(index) );
        text.remove( 0, index + 3 );
        index=text.find( " [" );
        if( index == -1 )
            break;
        performerList.append( text.left(index) );
        text.remove( 0, index + 2 );
        index = text.find( "]" );
        if( index == -1 )
            break;
        time = text.left( index );
        sscanf( time.local8Bit().data(), "%i:%i", &min, &sec );
        timeList.append( min * 60 + sec );
        text.remove( 0, index + 2 );
    }

    newText.append( "TITLE \"\"\n" );
    newText.append( "PERFORMER \"\"\n" );
    newText.append( "FILE \"\" MP3\n" );

    int TRACK = 1;
    int INDEX = 0;
    bool addFrames = false;
    TQStringList::Iterator performerIt = performerList.begin();
    TQValueList<int>::Iterator timeIt = timeList.begin();
    for( TQStringList::Iterator titleIt = titleList.begin(); titleIt != titleList.end(); ++titleIt )
    {
        newText.append( TQString().sprintf("  TRACK %02i AUDIO\n",TRACK ) );
        newText.append( "    TITLE \"" + (*titleIt) + "\"\n" );
        newText.append( "    PERFORMER \"" + (*performerIt) + "\"\n" );
        if( addFrames ) {
            newText.append( TQString().sprintf("    INDEX 01 %02i:%02i:37\n",INDEX/60,INDEX%60) );
            INDEX++;
            addFrames = false;
        }
        else {
            newText.append( TQString().sprintf("    INDEX 01 %02i:%02i:00\n",INDEX/60,INDEX%60) );
            addFrames = true;
        }

        performerIt++;
        timeIt++;
        TRACK++;
        INDEX += (*timeIt);
    }

    tTextEdit->setText(newText);
}

void CuesheetEditor::convert()
{
    TQString text=tTextEdit->text();
    TQString newText;
    TQString tmpText;
    TQString first, rest;
    TQStringList splinters;
    int index;

    while( index!=-1 )
    {
        index=text.find("\"");
        if( index==-1 )
            break;
        newText+=text.left(index+1);
        text.remove(0,index+1);
        index=text.find("\"");
        tmpText=text.left(index+1);
        text.remove(0,index+1);
        if( newText.right(6) == "FILE \"" )
        {
            newText+=tmpText;
            continue;
        }
        splinters=TQStringList::split(' ',tmpText);
        for( TQStringList::Iterator it=splinters.begin(); it!=splinters.end(); ++it )
        {
            for( uint i=0; i<(*it).length(); i++ )
            {
                if( (*it).left(i).lower() != (*it).left(i).upper() )
                {
                    index=i;
                    break;
                }
            }
            first=(*it).left(index);
            first=first.upper();
            rest=(*it).right((*it).length()-index);
            rest=rest.lower();
            for( uint i=0; i<rest.length(); i++ )
            {
                /*if( rest.mid(i,1).lower() == rest.mid(i,1).upper() )
                {
                    rest=rest.left(i+1)+rest.mid(i+1,1).upper()+rest.right(rest.length()-i-2);
                }*/
                if( rest.mid(i,1) == "-" )
                {
                    rest=rest.left(i+1)+rest.mid(i+1,1).upper()+rest.right(rest.length()-i-2);
                }
                if( rest.mid(i,1).lower() == "j" && rest.mid(i-1,1).lower() == "d" )
                {
                    rest=rest.left(i-1)+rest.mid(i-1,2).upper()+rest.right(rest.length()-i-1);
                }
                if( rest.mid(i,1).lower() == "j" && first.right(1).lower() == "d" )
                {
                    rest=rest.left(i)+rest.mid(i,1).upper()+rest.right(rest.length()-i-1);
                }
            }

            newText += first + rest + " ";
        }
        newText.remove( newText.length() - 1, 1 );
    }

    newText += text;

    tTextEdit->setText( newText );
}

void CuesheetEditor::shift() //move the title to "PERFORMER" and performer to "TITLE"
{
    TQString text = tTextEdit->text();
    TQString newText;
    TQString line, title="", performer="";
    int index;

    while( index !=- 1 )
    {
        index = text.find("\n");
        if( index == -1 )
            break;
        line = text.left(index+1);
        text.remove(0,index+1);
        // TODO clean up
        if( line.find( "TITLE" ) != -1 ) {
            line.replace( "TITLE", "PERFORMER" );
            if( performer != "" ) newText += performer;
            performer=line;
        }
        else if( line.find( "PERFORMER" ) != -1 ) {
            line.replace( "PERFORMER", "TITLE" );
            if( title != "" ) newText += title;
            title = line;
        }
        else {
            if( title != "" ) newText += title;
            if( performer != "" ) newText += performer;
            title = "";
            performer = "";
            newText += line;
        }

        if( title != "" && performer != "" ) {
            newText += title;
            newText += performer;
            title = "";
            performer = "";
        }
    }

    tTextEdit->setText( newText );
}


/*
void CuesheetEditor::shift() //replace title by performer and reverse
{
    TQString text=tTextEdit->text();
    TQString newText;
    TQString line, title, performer;
    int index;

    while( index!=-1 )
    {
        index=text.find("\n");
        if( index==-1 )
            break;
        line=text.left(index+1);
        text.remove(0,index+1);
        if( line.find("    TITLE \"") != -1 ) {
            line.replace("    TITLE \"","    PERFORMER \"");
            newText+=line;
        }
        else if( line.find("    PERFORMER \"") != -1 ) {
            line.replace("    PERFORMER \"","    TITLE \"");
            newText+=line;
        }
        else {
            newText+=line;
        }
    }

    tTextEdit->setText(newText);
}
*/

#include "cuesheeteditor.moc"