/***************************************************************************
                          kbarcode.cpp  -  description
                             -------------------
    begin                : Mit Jan 15 2003
    copyright            : (C) 2003 by Dominik Seichter
    email                : domseichter@web.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 "kbarcode.h"
#include "barkode.h"
#include "barcodedialog.h"
#include "batchwizard.h"
#include "labeleditor.h"
#include "databasebrowser.h"
#include "csvimportdlg.h"
#include "sqltables.h"
#include "kbarcodesettings.h"

// TQt includes
#include <tqgroupbox.h>
#include <tqlayout.h>

// KDE includes
#include <tdeaction.h>
#include <tdeapplication.h>
#include <tdecmdlineargs.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <tdepopupmenu.h>
#include <kpushbutton.h>
#include <tdemessagebox.h>

KBarcode::KBarcode( TQWidget *parent, const char *name, WFlags f)
    : DCOPObject("KBarcode"),
      DSMainWindow( parent, name, f )
{
    TQGroupBox* w = new TQGroupBox( this );
    w->setColumnLayout(0, TQt::Vertical );
    TQVBoxLayout* layout = new TQVBoxLayout( w->layout() );
    setCentralWidget( w );

    buttonSingle = new KPushButton( i18n("Barcode &Generator..."), w );
    buttonSingle->setEnabled( Barkode::haveBarcode() );
    buttonEditor = new KPushButton( i18n("&Label Editor..."), w );
    buttonBatch = new KPushButton( i18n("&Batch Printing..."), w );
    buttonData = new KPushButton( i18n("Edit SQL &Tables..."), w );
    buttonData->setEnabled( false );
    
    buttonSingle->setIconSet( BarIconSet( "barcode" ) );
    buttonEditor->setIconSet( BarIconSet( "edit" ) );
    buttonBatch->setIconSet( BarIconSet( "document-print" ) );

    layout->addWidget( buttonSingle );
    layout->addWidget( buttonEditor );
    layout->addWidget( buttonBatch );
    layout->addWidget( buttonData );

    connect( buttonSingle, TQ_SIGNAL( clicked() ), this,  TQ_SLOT( startBarcode() ) );
    connect( buttonEditor, TQ_SIGNAL( clicked() ), this,  TQ_SLOT( startLabelEditor() ) );
    connect( buttonBatch, TQ_SIGNAL( clicked() ), this,  TQ_SLOT( startBatchPrint() ) );
    connect( SqlTables::getInstance(), TQ_SIGNAL( connectedSQL() ), this,  TQ_SLOT( enableData() ) );
    
    setupActions();
    show();

    TDEAction* editLabelDefAct = new TDEAction(i18n("&Edit Label Definitions"), "",
                                0, this,  TQ_SLOT(editLabelDef()), actionCollection(), "design" );

    TDEAction* editArticleAct = new TDEAction(i18n("&Edit Articles"), "",
                                0, this,  TQ_SLOT(editArticles()), actionCollection(), "design" );

    TDEAction* editCustomerAct = new TDEAction(i18n("&Edit Customers"), "",
                                0, this,  TQ_SLOT(editCustomers()), actionCollection(), "design" );

    TDEAction* editCustomerTextAct = new TDEAction(i18n("&Edit Customer Text"), "",
                                0, this,  TQ_SLOT(editCustomerText()), actionCollection() );

    TDEAction* importCSVAct = new TDEAction(i18n("&Import CSV File..."), "",
                                0, this,  TQ_SLOT(importCSV()), actionCollection() );
                                
    TDEPopupMenu* data = new TDEPopupMenu( buttonData );
    editLabelDefAct->plug( data );
    editArticleAct->plug( data );
    editCustomerAct->plug( data );
    editCustomerTextAct->plug( data );
    buttonData->setPopup( data );
    data->insertSeparator();
    importCSVAct->plug( data );

    enableData();
}

KBarcode::~KBarcode()
{
    DSMainWindow::saveConfig();
}

void KBarcode::setupActions()
{
    DSMainWindow::setupActions();
}

void KBarcode::startBarcode()
{
    new BarCodeDialog();
}

void KBarcode::startLabelEditor()
{
    LabelEditor* ed = new LabelEditor( NULL, TQString(), "LabelEditorWindow" );
    ed->startupDlg( LabelEditor::eCreateNewLabel, TQString() );
}

void KBarcode::startBatchPrint()
{
    new BatchWizard( this );
}

void KBarcode::editArticles()
{
    new DatabaseBrowser( TABLE_BASIC, NULL, "basicbrowser" );
}

void KBarcode::editCustomers()
{
    new DatabaseBrowser( TABLE_CUSTOMER, NULL, "customerbrowser" );
}

void KBarcode::editCustomerText()
{
    new DatabaseBrowser( TABLE_CUSTOMER_TEXT, NULL, "customertextbrowser" );
}

void KBarcode::editLabelDef()
{
    new DatabaseBrowser( TABLE_LABEL_DEF, NULL, "defbrowser" );
}

void KBarcode::enableData()
{
    buttonData->setEnabled( SqlTables::getInstance()->isConnected() );
}

bool KBarcode::parseCmdLine()
{
    enum { BARCODE, LABEL, BATCH, NONE } mode = NONE;

    TDECmdLineArgs* args = TDECmdLineArgs::parsedArgs();

    BatchPrinter::EOutputFormat eFormat = BatchPrinter::POSTSCRIPT;
    LabelEditor* pEdit = NULL;
    TQString serial;
    TQString sqlquery   = TQString();
    TQString csvfile    = TQString();
    TQString printer    = TQString();

    bool bPrintNow     = args->isSet("print");
    int serialinc      = 0;
    int numlabels      = -1;

    TQString format = args->getOption("output");
    if( format.upper() == "BARCODE" )
	eFormat = BatchPrinter::BCP;
    else if( format.upper() == "IMAGE" )
	eFormat = BatchPrinter::IMAGE;
    else if( format.upper() == "POSTSCRIPT" )
	eFormat = BatchPrinter::POSTSCRIPT;
    else
    {
	KMessageBox::error( this, i18n("%1 is no valid output format for --output. Valid values are POSTSCRIPT, IMAGE and BARCODE.").arg( format ) );
    }

    if( args->isSet("barcode") )
    {
	mode = BARCODE;
	startBarcode();
    }

    if( args->isSet("batch") )
	mode = BATCH;
    
    if( args->isSet("label") )
	mode = LABEL;

    if( args->isSet("serialnumber") )
    {
	serial = args->getOption("serialnumber");
	if( args->isSet("serialinc") )
	    serialinc = args->getOption("serialinc").toInt();
    }

    if( args->isSet("numlabels") )
	numlabels = args->getOption("numlabels").toInt();

    if( args->isSet("importsql") )
	sqlquery = args->getOption("importsql");

    if( args->isSet("importcsv") ) 
	csvfile = args->getOption("importcsv");

    if( args->isSet("printer") )
	printer = args->getOption("printer");

    for( int i = 0; i < args->count(); i++) 
	if( mode == BATCH )
	{
	    BatchWizard* b = new BatchWizard();
	    b->setFilename( args->url( i ).path() );
	    b->setOutputFormat( eFormat );
	    b->setSerialNumber( serial, serialinc );
	    if( !sqlquery.isEmpty() )
		b->setImportSqlQuery( sqlquery );

	    if( !csvfile.isEmpty() )
		b->setImportCsvFile( csvfile );

	    if( numlabels != -1 )
		b->setNumLabels( numlabels );

	    if( bPrintNow )
            {
		b->printNow( printer, false );
                delete b;
            }
	}
	else
        {
	    pEdit = new LabelEditor( 0, args->url( i ).path() );
            if( bPrintNow )
                // TODO: use the printer set by the printer commandline option
                pEdit->print(); 
        }

    if( !args->count() && mode == LABEL )
    {
        pEdit = new LabelEditor();
        if( bPrintNow )
            // TODO: use the printer set by the printer commandline option
            pEdit->print(); 

    }

    int argc = args->count();
    args->clear();  // Free some memory

    // close after printing
    if( bPrintNow && argc )
    {
        // TODO: really close the whole application
        this->close();
        return true;
    }
    else
        return false;    
}

void KBarcode::importCSV()
{
    new CSVImportDlg( this, "csvimportdlg" );
}

bool KBarcode::isSQLConnected() const
{
    return SqlTables::isConnected();
}

bool KBarcode::connectSQL()
{
    return SqlTables::getInstance()->connectMySQL();
}

void KBarcode::showWizard()
{
    DSMainWindow::wizard();
}

void KBarcode::showConfigure()
{
    KBarcodeSettings::getInstance()->configure();
}


#include "kbarcode.moc"
