/*******************************************************************
 KNotes -- Notes for the KDE project

 Copyright (c) 2002-2004, Michael Brade <brade@kde.org>

 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*******************************************************************/

#include <tqfile.h>
#include <tqfont.h>
#include <tqpoint.h>
#include <tqcolor.h>
#include <tqstringlist.h>
#include <tqtextstream.h>

#include <kdebug.h>
#include <tdeapplication.h>
#include <tdeglobal.h>
#include <kurl.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <tdeio/netaccess.h>

#include <unistd.h>

#include "knoteslegacy.h"
#include "knoteconfig.h"
#include "version.h"

#include "libkcal/calendarlocal.h"
#include "libkcal/journal.h"

#include <netwm.h>

using namespace KCal;


void KNotesLegacy::cleanUp()
{
    // remove old (KDE 1.x) local config file if it still exists
    TQString configfile = TDEGlobal::dirs()->saveLocation( "config" ) + "knotesrc";
    if ( TQFile::exists( configfile ) ) {
        KSimpleConfig *test = new KSimpleConfig( configfile );
        test->setGroup( "General" );
        double version = test->readDoubleNumEntry( "version", 1.0 );
        delete test;

        if ( version == 1.0 ) {
            if ( !( checkAccess( configfile, W_OK ) &&
                    TQFile::remove( configfile ) ) )
            {
                kdError(5500) << k_funcinfo << "Could not delete old config file " << configfile << endl;
            }
        }
    }
}

bool KNotesLegacy::convert( CalendarLocal *calendar )
{
    bool converted = false;

    TQDir noteDir( TDEGlobal::dirs()->saveLocation( "appdata", "notes/" ) );
    const TQStringList notes = noteDir.entryList( TQDir::Files, TQDir::Name );
    for ( TQStringList::ConstIterator note = notes.constBegin(); note != notes.constEnd(); ++note )
    {
        TQString file = noteDir.absFilePath( *note );
        KSimpleConfig* test = new KSimpleConfig( file );
        test->setGroup( "General" );
        double version = test->readDoubleNumEntry( "version", 1.0 );

        if ( version < 3.0 )
        {

            // create the new note
            Journal *journal = new Journal();
            bool success;

            if ( version < 2.0 )
                success = convertKNotes1Config( journal, noteDir, *note );
            else
                success = convertKNotes2Config( journal, noteDir, *note );

            // could not convert file => do not add a new note
            if ( !success )
                delete journal;
            else
            {
                calendar->addJournal( journal );
                converted = true;
            }
        }
        // window state changed for version 3.2
        else if ( version < 3.2 )
        {
            uint state = test->readUnsignedLongNumEntry( "state", NET::SkipTaskbar );
            test->writeEntry( "ShowInTaskbar", (state & NET::SkipTaskbar) ? false : true );
            test->writeEntry( "KeepAbove", (state & NET::KeepAbove) ? true : false );
            test->deleteEntry( "state" );
        }
        delete test;	
    }

    return converted;
}

bool KNotesLegacy::convertKNotes1Config( Journal *journal, TQDir& noteDir,
        const TQString& file )
{
    TQFile infile( noteDir.absFilePath( file ) );
    if ( !infile.open( IO_ReadOnly ) )
    {
        kdError(5500) << k_funcinfo << "Could not open input file: \""
                      << infile.name() << "\"" << endl;
        return false;
    }

    TQTextStream input( &infile );

    // get the name
    journal->setSummary( input.readLine() );

    TQStringList props = TQStringList::split( '+', input.readLine() );

    // robustness
    if ( props.count() != 13 )
    {
        kdWarning(5500) << k_funcinfo << "The file \"" << infile.name()
                        << "\" lacks version information but is not a valid "
                        << "KNotes 1 config file either!" << endl;
        return false;
    }

    // the new configfile's name
    TQString configFile = noteDir.absFilePath( journal->uid() );

    // set the defaults
    TDEIO::NetAccess::copy(
        KURL( TDEGlobal::dirs()->saveLocation( "config" ) + "knotesrc" ),
        KURL( configFile ),
        0
    );

    KNoteConfig config( TDESharedConfig::openConfig( configFile, false, false ) );
    config.readConfig();
    config.setVersion( KNOTES_VERSION );

    // get the geometry
    config.setWidth( props[3].toUInt() );
    config.setHeight( props[4].toUInt() );

    // get the background color
    uint red = input.readLine().toUInt();
    uint green = input.readLine().toUInt();
    uint blue = input.readLine().toUInt();
    config.setBgColor( TQColor( red, green, blue ) );

    // get the foreground color
    red = input.readLine().toUInt();
    green = input.readLine().toUInt();
    blue = input.readLine().toUInt();
    config.setFgColor( TQColor( red, green, blue ) );

    // get the font
    TQString fontfamily = input.readLine();
    if ( fontfamily.isEmpty() )
        fontfamily = TQString( "Sans Serif" );
    uint size = input.readLine().toUInt();
    size = TQMAX( size, 4 );
    uint weight = input.readLine().toUInt();
    bool italic = ( input.readLine().toUInt() == 1 );
    TQFont font( fontfamily, size, weight, italic );

    config.setTitleFont( font );
    config.setFont( font );

    // 3d frame? Not supported yet!
    input.readLine();

    // autoindent
    config.setAutoIndent( input.readLine().toUInt() == 1 );

    // KNotes 1 never had rich text
    config.setRichText( false );

    int note_desktop = props[0].toUInt();

    // hidden or on all desktops?
    if ( input.readLine().toUInt() == 1 )
        note_desktop = 0;
    else if ( props[11].toUInt() == 1 )
        note_desktop = NETWinInfo::OnAllDesktops;

    config.setDesktop( note_desktop );
    config.setPosition( TQPoint( props[1].toUInt(), props[2].toUInt() ) );
    config.setKeepAbove( props[12].toUInt() & 2048 );

    config.writeConfig();

    // get the text
    TQString text;
    while ( !input.atEnd() )
    {
        text.append( input.readLine() );
        if ( !input.atEnd() )
            text.append( '\n' );
    }

    journal->setDescription( text );

    if ( !infile.remove() )
        kdWarning(5500) << k_funcinfo << "Could not delete input file: \"" << infile.name() << "\"" << endl;

    return true;
}

bool KNotesLegacy::convertKNotes2Config( Journal *journal, TQDir& noteDir,
        const TQString& file )
{
    TQString configFile = noteDir.absFilePath( journal->uid() );

    // new name for config file
    if ( !noteDir.rename( file, journal->uid() ) )
    {
        kdError(5500) << k_funcinfo << "Could not rename input file: \""
                      << noteDir.absFilePath( file ) << "\" to \""
                      << configFile << "\"!" << endl;
        return false;
    }

    // update the config
    TDEConfig config( configFile );
    config.setGroup( "Data" );
    journal->setSummary( config.readEntry( "name" ) );
    config.deleteGroup( "Data", true );
    config.setGroup( "General" );
    config.writeEntry( "version", KNOTES_VERSION );
    config.setGroup( "WindowDisplay" );
    uint state = config.readUnsignedLongNumEntry( "state", NET::SkipTaskbar );
    config.writeEntry( "ShowInTaskbar", (state & NET::SkipTaskbar) ? false : true );
    config.writeEntry( "KeepAbove", (state & NET::KeepAbove) ? true : false );
    config.deleteEntry( "state" );

    // load the saved text and put it in the journal
    TQFile infile( noteDir.absFilePath( "." + file + "_data" ) );
    if ( infile.open( IO_ReadOnly ) )
    {
        TQTextStream input( &infile );
        input.setEncoding( TQTextStream::UnicodeUTF8 );
        journal->setDescription( input.read() );
        if ( !infile.remove() )
            kdWarning(5500) << k_funcinfo << "Could not delete data file: \"" << infile.name() << "\"" << endl;
    }
    else
        kdWarning(5500) << k_funcinfo << "Could not open data file: \"" << infile.name() << "\"" << endl;

    return true;
}
