/* This file is part of the KDE project
  Copyright (C) 2002-2004 Alexander Dymo <cloudtemple@mksat.net>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MEm_viewHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/
#include "kudesigner_view.h"
#include "kudesigner_factory.h"
#include "kudesigner_doc.h"

#include <map>

#include <tqpainter.h>
#include <tqiconset.h>
#include <tqinputdialog.h>
#include <tqevent.h>
#include <tqmainwindow.h>
#include <tqaction.h>
#include <tqlayout.h>
#include <tqdockwindow.h>
#include <tqmenubar.h>
#include <tqmessagebox.h>
#include <tqspinbox.h>
#include <tqlabel.h>

#include <tdeaction.h>
#include <kstdaction.h>
#include <tdelocale.h>
#include <kdebug.h>

#include <KoMainWindow.h>

#include <commdefs.h>
#include <view.h>
#include <structurewidget.h>
#include <canvas.h>
#include <command.h>

#include <field.h>
#include <calcfield.h>
#include <label.h>
#include <line.h>
#include <specialfield.h>

#include <kugartemplate.h>
#include <reportheader.h>
#include <reportfooter.h>
#include <pageheader.h>
#include <pagefooter.h>
#include <detailheader.h>
#include <detailfooter.h>
#include <detail.h>

#include <koproperty/editor.h>
#include <koproperty/property.h>

using namespace Kudesigner;

KudesignerView::KudesignerView( KudesignerDoc* part, TQWidget* parent, const char* name )
        : KoView( part, parent, name ), m_propertyEditor( 0 ), m_doc( part )
{
    setInstance( KudesignerFactory::global() );
    if ( !part->isReadWrite() )  // readonly case, e.g. when embedded into konqueror
        setXMLFile( "kudesigner_readonly.rc" ); // simplified GUI
    else
        setXMLFile( "kudesignerui.rc" );

    TQVBoxLayout *l = new TQVBoxLayout( this, 0, 0 );
    m_view = new Kudesigner::View( part->canvas(), this );
    if ( part->plugin() )
    {
        m_view->setAcceptDrops( part->plugin() ->acceptsDrops() );
        m_view->viewport() ->setAcceptDrops( part->plugin() ->acceptsDrops() );
        m_view->setPlugin( part->plugin() );
    }
    l->addWidget( m_view );

    m_view->viewport() ->setFocusProxy( m_view );
    m_view->viewport() ->setFocusPolicy( TQWidget::WheelFocus );
    m_view->setFocus();

    m_view->itemToInsert = 0;

    TQDockWindow *dw1 = new TQDockWindow( TQDockWindow::OutsideDock, shell() );
    TQDockWindow *dw2 = new TQDockWindow( TQDockWindow::OutsideDock, shell() );
    m_structure = new Kudesigner::StructureWidget( dw1 );
    m_propertyEditor = new Editor( dw2 );
    dw1->boxLayout() ->addWidget( m_structure, 1 );
    dw2->boxLayout() ->addWidget( m_propertyEditor, 1 );
    dw1->setFixedExtentWidth( 400 );
    dw1->setResizeEnabled( true );
    dw2->setFixedExtentWidth( 400 );
    dw2->setResizeEnabled( true );

    if ( m_doc->plugin() )
    {
        //                 connect( m_propertyEditor, TQ_SIGNAL(createPluggedInEditor(TQWidget*&, Editor *, Property*, Box *)),
        //                          m_doc->plugin(), TQ_SLOT(createPluggedInEditor(TQWidget*&, Editor *, Property*, Box *)));

        kdDebug() << "*************Property and plugin have been connected" << endl;
    }

    shell() ->addDockWindow( dw1, m_doc->propertyPosition() );
    shell() ->addDockWindow( dw2, m_doc->propertyPosition() );

    m_structure->setDocument( m_doc->canvas() );

    connect( m_doc, TQ_SIGNAL( canvasChanged( Kudesigner::Canvas * ) ),
             m_structure, TQ_SLOT( setDocument( Kudesigner::Canvas * ) ) );
    connect( m_doc->canvas(), TQ_SIGNAL( structureModified() ),
             m_structure, TQ_SLOT( refresh() ) );

    connect( m_view, TQ_SIGNAL( selectionMade( Buffer* ) ),
             this, TQ_SLOT( populateProperties( Buffer* ) ) );

    connect( m_view, TQ_SIGNAL( selectionClear() ),
             m_propertyEditor, TQ_SLOT( clear() ) );

    connect( m_view, TQ_SIGNAL( changed() ),
             m_doc, TQ_SLOT( setModified() ) );

    connect( m_view, TQ_SIGNAL( selectionMade( Buffer* ) ),
             m_structure, TQ_SLOT( selectionMade() ) );
    connect( m_view, TQ_SIGNAL( selectionClear() ),
             m_structure, TQ_SLOT( selectionClear() ) );

    connect( m_view, TQ_SIGNAL( selectedActionProcessed() ), this, TQ_SLOT( unselectItemAction() ) );
    connect( m_view, TQ_SIGNAL( modificationPerformed() ), part, TQ_SLOT( setModified() ) );
    connect( m_view, TQ_SIGNAL( itemPlaced( int, int, int, int ) ), this, TQ_SLOT( placeItem( int, int, int, int ) ) );

    gridLabel = new TQLabel( i18n( "Grid size:" ), shell() );
    gridBox = new TQSpinBox( 1, 100, 1, shell() );
    gridBox->setValue( 10 );
    connect( gridBox, TQ_SIGNAL( valueChanged( int ) ), m_view, TQ_SLOT( setGridSize( int ) ) );

    initActions();

    show();
    m_view->show();
    m_structure->refresh();
}

KudesignerView::~KudesignerView()
{
    delete gridLabel;
    delete gridBox;
}

void KudesignerView::paintEvent( TQPaintEvent* ev )
{
    TQPainter painter;
    painter.begin( this );

    // ### TODO: Scaling

    // Let the document do the drawing
    koDocument() ->paintEverything( painter, ev->rect(), false, this );

    painter.end();
}

void KudesignerView::resizeEvent( TQResizeEvent* /*_ev*/ )
{
    m_view->setGeometry( 0, 0, width(), height() );
}

void KudesignerView::initActions()
{
    cutAction = KStdAction::cut( this, TQ_SLOT( cut() ), actionCollection() );
    copyAction = KStdAction::copy( this, TQ_SLOT( copy() ), actionCollection() );
    pasteAction = KStdAction::paste( this, TQ_SLOT( paste() ), actionCollection() );
    selectAllAction = KStdAction::selectAll( this, TQ_SLOT( selectAll() ), actionCollection() );
    deleteAction = new TDEAction( i18n( "Delete" ), "edit-delete", 0, this,
                                TQ_SLOT( deleteItems() ), actionCollection(), "edit_delete" );
    cutAction->setEnabled( false );
    copyAction->setEnabled( false );
    pasteAction->setEnabled( false );
    //    deleteAction->setEnabled(false);

    sectionsReportHeader = new TDEAction( i18n( "Report Header" ), "irh", 0, this,
                                        TQ_SLOT( slotAddReportHeader() ), actionCollection(), "rheader" );
    sectionsReportFooter = new TDEAction( i18n( "Report Footer" ), "irf", 0, this,
                                        TQ_SLOT( slotAddReportFooter() ), actionCollection(), "rfooter" );
    sectionsPageHeader = new TDEAction( i18n( "Page Header" ), "iph", 0, this,
                                      TQ_SLOT( slotAddPageHeader() ), actionCollection(), "pheader" );
    sectionsPageFooter = new TDEAction( i18n( "Page Footer" ), "ipf", 0, this,
                                      TQ_SLOT( slotAddPageFooter() ), actionCollection(), "pfooter" );
    sectionsDetailHeader = new TDEAction( i18n( "Detail Header" ), "idh", 0, this,
                                        TQ_SLOT( slotAddDetailHeader() ), actionCollection(), "dheader" );
    sectionsDetail = new TDEAction( i18n( "Detail" ), "id", 0, this,
                                  TQ_SLOT( slotAddDetail() ), actionCollection(), "detail" );
    sectionsDetailFooter = new TDEAction( i18n( "Detail Footer" ), "idf", 0, this,
                                        TQ_SLOT( slotAddDetailFooter() ), actionCollection(), "dfooter" );

    itemsNothing = new TDERadioAction( i18n( "Clear Selection" ), "frame_edit", 0, this,
                                     TQ_SLOT( slotAddItemNothing() ), actionCollection(), "nothing" );
    itemsNothing->setExclusiveGroup( "itemsToolBar" );
    itemsNothing->setChecked( true );
    itemsLabel = new TDERadioAction( i18n( "Label" ), "frame_text", 0, this,
                                   TQ_SLOT( slotAddItemLabel() ), actionCollection(), "label" );
    itemsLabel->setExclusiveGroup( "itemsToolBar" );
    itemsField = new TDERadioAction( i18n( "Field" ), "frame_field", 0, this,
                                   TQ_SLOT( slotAddItemField() ), actionCollection(), "field" );
    itemsField->setExclusiveGroup( "itemsToolBar" );
    itemsSpecial = new TDERadioAction( i18n( "Special Field" ), "frame_query", 0, this,
                                     TQ_SLOT( slotAddItemSpecial() ), actionCollection(), "special" );
    itemsSpecial->setExclusiveGroup( "itemsToolBar" );
    itemsCalculated = new TDERadioAction( i18n( "Calculated Field" ), "frame_formula", 0, this,
                                        TQ_SLOT( slotAddItemCalculated() ), actionCollection(), "calcfield" );
    itemsCalculated->setExclusiveGroup( "itemsToolBar" );
    itemsLine = new TDERadioAction( i18n( "Line" ), "frame_chart", 0, this,
                                  TQ_SLOT( slotAddItemLine() ), actionCollection(), "line" );
    itemsLine->setExclusiveGroup( "itemsToolBar" );

    gridActionLabel = new KWidgetAction( gridLabel, i18n( "Grid Label" ), 0, this,
                                         0, actionCollection(), "gridlabel" );

    gridAction = new KWidgetAction( gridBox, i18n( "Grid Size" ), 0, this,
                                    0, actionCollection(), "gridaction" );
}

void KudesignerView::updateReadWrite( bool /*readwrite*/ )
{
}

void KudesignerView::guiActivateEvent( KParts::GUIActivateEvent *ev )
{
    if ( ev->activated() )
        m_propertyEditor->show();
    else
        m_propertyEditor->hide();
    KoView::guiActivateEvent( ev );
}

void KudesignerView::populateProperties( Buffer *buf )
{
    connect( buf, TQ_SIGNAL( propertyChanged() ), m_doc->canvas(), TQ_SLOT( changed() ) );
    m_propertyEditor->changeSet( buf );
}

void KudesignerView::cut()
{
    //    kdDebug(31000) << "KudesignerView::cut(): CUT called" << endl;
}

void KudesignerView::copy()
{
    //    kdDebug(31000) << "KudesignerView::copy(): COPY called" << endl;
}

void KudesignerView::paste( )
{}

void KudesignerView::deleteItems( )
{
    if ( m_doc->canvas() ->selected.count() > 0 )
        m_doc->addCommand( new DeleteReportItemsCommand( m_doc->canvas(), m_doc->canvas() ->selected ) );
}

void KudesignerView::selectAll( )
{
    m_doc->canvas() ->selectAll();
}

void KudesignerView::slotAddReportHeader()
{
    if ( !( ( ( KudesignerDoc * ) ( koDocument() ) ) ) ->canvas() ->kugarTemplate() ->reportHeader )
    {
        m_doc->addCommand( new AddReportHeaderCommand( m_doc->canvas() ) );
    }
}

void KudesignerView::slotAddReportFooter()
{
    if ( !( ( ( KudesignerDoc * ) ( koDocument() ) ) ) ->canvas() ->kugarTemplate() ->reportFooter )
    {
        m_doc->addCommand( new AddReportFooterCommand( m_doc->canvas() ) );
    }
}

void KudesignerView::slotAddPageHeader()
{
    if ( !( ( ( KudesignerDoc * ) ( koDocument() ) ) ) ->canvas() ->kugarTemplate() ->pageHeader )
    {
        m_doc->addCommand( new AddPageHeaderCommand( m_doc->canvas() ) );
    }
}

void KudesignerView::slotAddPageFooter()
{
    if ( !( ( ( KudesignerDoc * ) ( koDocument() ) ) ) ->canvas() ->kugarTemplate() ->pageFooter )
    {
        m_doc->addCommand( new AddPageFooterCommand( m_doc->canvas() ) );
    }
}

void KudesignerView::slotAddDetailHeader()
{
    bool Ok = false;
    unsigned int level = TQInputDialog::getInteger( tr( "Add Detail Header" ), tr( "Enter detail level:" ),
                         0, 0, 100, 1, &Ok, this );
    if ( !Ok )
        return ;
    if ( m_doc->canvas() ->kugarTemplate() ->detailsCount >= level )
    {
        m_doc->addCommand( new AddDetailHeaderCommand( level, m_doc->canvas() ) );
    }
}

void KudesignerView::slotAddDetail()
{
    bool Ok = false;
    unsigned int level = TQInputDialog::getInteger( tr( "Add Detail" ), tr( "Enter detail level:" ),
                         0, 0, 100, 1, &Ok, this );
    if ( !Ok )
        return ;
    if ( ( ( level == 0 ) && ( m_doc->canvas() ->kugarTemplate() ->detailsCount == 0 ) )
            || ( m_doc->canvas() ->kugarTemplate() ->detailsCount == level ) )
    {
        m_doc->addCommand( new AddDetailCommand( level, m_doc->canvas() ) );
    }
}

void KudesignerView::slotAddDetailFooter()
{
    bool Ok = false;
    unsigned int level = TQInputDialog::getInteger( tr( "Add Detail Footer" ), tr( "Enter detail level:" ),
                         0, 0, 100, 1, &Ok, this );
    if ( !Ok )
        return ;

    if ( m_doc->canvas() ->kugarTemplate() ->detailsCount >= level )
    {
        m_doc->addCommand( new AddDetailFooterCommand( level, m_doc->canvas() ) );
    }
}

void KudesignerView::slotAddItemNothing()
{
    if ( m_doc->canvas() )
    {
        if ( m_view->itemToInsert )
        {
            m_view->itemToInsert = 0;
        }
    }
}

void KudesignerView::slotAddItemLabel()
{
    if ( m_doc->canvas() )
    {
        m_view->itemToInsert = Rtti_Label;
    }
}

void KudesignerView::slotAddItemField()
{
    if ( m_doc->canvas() )
    {
        m_view->itemToInsert = Rtti_Field;
    }
}

void KudesignerView::slotAddItemSpecial()
{
    if ( m_doc->canvas() )
    {
        m_view->itemToInsert = Rtti_Special;
    }
}

void KudesignerView::slotAddItemCalculated()
{
    if ( m_doc->canvas() )
    {
        m_view->itemToInsert = Rtti_Calculated;
    }
}

void KudesignerView::slotAddItemLine()
{
    if ( m_doc->canvas() )
    {
        m_view->itemToInsert = Rtti_Line;
    }
}

void KudesignerView::unselectItemAction()
{
    /*    itemsNothing->setOn(true);*/
}

void KudesignerView::placeItem( int x, int y, int band, int bandLevel )
{
    m_doc->addCommand( new AddReportItemCommand( m_doc->canvas(), m_view, x, y, ( Kudesigner::RttiValues ) band, bandLevel ) );
}

#include "kudesigner_view.moc"
