/* This file is part of the KDE project
   Copyright (C) 2003 Peter Simonsson <psn@linux.se>,
   theKompany.com & Dave Marotti

   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
   MERCHANTABILITY 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 "kiviostencilsetaction.h"

#include <tdepopupmenu.h>
#include <kstandarddirs.h>
#include <tdeapplication.h>
#include <kdebug.h>
#include <tdetoolbar.h>
#include <tdetoolbarbutton.h>
#include <kiconloader.h>
#include <tdelocale.h>

#include <tqfile.h>
#include <tqdir.h>
#include <tqpixmap.h>
#include <tqwhatsthis.h>
#include <tqmenubar.h>
#include <tqstringlist.h>
#include <tqvaluelist.h>

#include "kivio_stencil_spawner_set.h"

static const char * default_plug_xpm[] = {
"16 16 5 1",
" 	c None",
".	c #000000",
"+	c #C4C7FF",
"@	c #5961FF",
"#	c #FFFFFF",
"                ",
"                ",
" ...            ",
" .++..          ",
" .+@++..        ",
" .+@@@++..      ",
" .+@@@@@++..    ",
" .+@@@@@@@++..  ",
" .+@@@@@@@@@++. ",
" .+@@@@@@@@@@@.#",
" .+@@@@@@@@@@@.#",
" .+@@@@@@@@@@@.#",
" .+@@@@@@@@@@@.#",
" .+@@@@@@@@@@@.#",
" ..............#",
"  ##############"};

KivioStencilSetAction::KivioStencilSetAction(const TQString &text, const TQString &pix,
  TDEActionCollection *parent, const char *name)
  : TDEAction(text, pix, 0, parent, name)
{
  setShortcutConfigurable( false );

  m_pathList.setAutoDelete(true);

  m_popup = new TDEPopupMenu(0L,"KivioStencilSetAction::popup");
  updateMenu();
}

KivioStencilSetAction::~KivioStencilSetAction()
{
  clearCollectionMenuList();
  delete m_popup;
  m_popup = 0;
}

TDEPopupMenu* KivioStencilSetAction::popupMenu() const
{
  return m_popup;
}

void KivioStencilSetAction::popup( const TQPoint& global )
{
  popupMenu()->popup(global);
}

int KivioStencilSetAction::plug( TQWidget* widget, int index)
{
  // This function is copied from TDEActionMenu::plug
  if (kapp && !kapp->authorizeTDEAction(name()))
    return -1;
  kdDebug(129) << "TDEAction::plug( " << widget << ", " << index << " )" << endl; // remove -- ellis
  if ( widget->inherits(TQPOPUPMENU_OBJECT_NAME_STRING) )
  {
    TQPopupMenu* menu = static_cast<TQPopupMenu*>( widget );
    int id;

    if ( hasIconSet() )
      id = menu->insertItem( iconSet(), text(), popupMenu(), -1, index );
    else
      id = menu->insertItem( kapp->iconLoader()->loadIcon(icon(), TDEIcon::Small),
        text(), popupMenu(), -1, index );

    if ( !isEnabled() )
      menu->setItemEnabled( id, false );

    addContainer( menu, id );
    connect( menu, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotDestroyed() ) );

    return containerCount() - 1;
  }
  else if ( widget->inherits( "TDEToolBar" ) )
  {
    TDEToolBar *bar = static_cast<TDEToolBar *>( widget );

    int id_ = TDEAction::getToolButtonID();

    if ( icon().isEmpty() && !iconSet().isNull() )
      bar->insertButton( iconSet().pixmap(), id_, TQT_SIGNAL( clicked() ), this,
                          TQT_SLOT( slotActivated() ), isEnabled(), plainText(),
                          index );
    else
    {
      TDEInstance *instance;

      if ( m_parentCollection )
        instance = m_parentCollection->instance();
      else
        instance = TDEGlobal::instance();

      bar->insertButton( icon(), id_, TQT_SIGNAL( clicked() ), this,
                          TQT_SLOT( slotActivated() ), isEnabled(), plainText(),
                          index, instance );
    }

    addContainer( bar, id_ );

    if (!whatsThis().isEmpty())
      TQWhatsThis::add( bar->getButton(id_), whatsThis() );

    connect( bar, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotDestroyed() ) );

    bar->getButton(id_)->setPopup(popupMenu(), true );

    return containerCount() - 1;
  }
  else if ( widget->inherits( TQMENUBAR_OBJECT_NAME_STRING ) )
  {
    TQMenuBar *bar = static_cast<TQMenuBar *>( widget );

    int id;

    id = bar->insertItem( text(), popupMenu(), -1, index );

    if ( !isEnabled() )
      bar->setItemEnabled( id, false );

    addContainer( bar, id );
    connect( bar, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( slotDestroyed() ) );

    return containerCount() - 1;
  }

  return -1;
}

void KivioStencilSetAction::updateMenu()
{
  m_ssId = 0;
  m_popup->clear();

  m_popup->insertItem(i18n("Show Stencil Set Chooser"), this, TQT_SIGNAL(showDialog()));
  m_popup->insertSeparator();

  m_pathList.clear();
  m_collectionIdList.clear();
  clearCollectionMenuList();

  TDEStandardDirs *dirs = TDEGlobal::dirs();
  TQStringList dirList = dirs->findDirs("data", "kivio/stencils");
  dirList.sort();

  for( TQStringList::Iterator it = dirList.begin(); it != dirList.end(); ++it )
  {
    TQString dir = (*it);
    loadCollections(dir);
  }
}

void KivioStencilSetAction::loadCollections( const TQString& rootDirStr )
{
  TQDir rootDir( rootDirStr );

  rootDir.setFilter( TQDir::Dirs );
  rootDir.setSorting( TQDir::Name );

  const TQFileInfoList *colList = rootDir.entryInfoList();
  TQFileInfoListIterator colIt( *colList );
  TQFileInfo *colFInfo;
  TQString cId;

  while((colFInfo = colIt.current()))
  {
    if(colFInfo->fileName() != ".." && colFInfo->fileName() != ".")
    {
      cId = KivioStencilSpawnerSet::readId(colFInfo->absFilePath());
      TDEPopupMenu* ch;
      int index = m_collectionIdList.findIndex(cId);
      
      if(index < 0) {
        ch = new TDEPopupMenu;
        connect(ch,TQT_SIGNAL(activated(int)),TQT_SLOT(slotActivated(int)));
        m_popup->insertItem(TQIconSet(dirtPixmap(colFInfo->absFilePath())),
          KivioStencilSpawnerSet::readTitle(colFInfo->absFilePath()),ch);
        m_collectionIdList.append(cId);
        m_collectionMenuList.append(ch);
      } else {
        ch = m_collectionMenuList[index];
      }
    
      loadSet( ch, rootDirStr + "/" + colFInfo->fileName() );
    }
    
    ++colIt;
  }
}

void KivioStencilSetAction::loadSet( TDEPopupMenu* menu, const TQString& rootDirStr )
{
  TQDir rootDir( rootDirStr );

  rootDir.setFilter( TQDir::Dirs );
  rootDir.setSorting( TQDir::Name );

  const TQFileInfoList *setList = rootDir.entryInfoList();
  TQFileInfoListIterator setIt( *setList );
  TQFileInfo *setFInfo;

  while( (setFInfo = setIt.current()) )
  {
    if( setFInfo->fileName() != ".." && setFInfo->fileName() != "." )
    {
      menu->insertItem(TQIconSet(dirtPixmap(setFInfo->absFilePath())),
        KivioStencilSpawnerSet::readTitle(setFInfo->absFilePath()),m_ssId);
      m_pathList.insert( m_ssId, new TQString(rootDirStr + "/" + setFInfo->fileName()) );
      m_ssId++;
    }
    ++setIt;
  }
}

TQPixmap KivioStencilSetAction::dirtPixmap( const TQString& dir )
{
    TQString fs;

    if( TQFile::exists(dir + "/icon.xpm") ) {
      fs = dir + "/icon.xpm";
    } else if( TQFile::exists(dir + "/icon.png") ) {
      fs = dir + "/icon.png";
    } else {
      return TQPixmap( (const char **)default_plug_xpm );
    }

    TQFile file( fs );
    TQFileInfo finfo( file );
    return TQPixmap( finfo.absFilePath() );
}

void KivioStencilSetAction::slotActivated(int id)
{
  if (id < 0 || !m_pathList.at((uint)id))
    return;

  TQString path = *m_pathList.at((uint)id);

  emit activated(path);
}

void KivioStencilSetAction::clearCollectionMenuList()
{
  TQValueList<TDEPopupMenu*>::Iterator it;
  
  for(it = m_collectionMenuList.begin(); it != m_collectionMenuList.end(); ++it) {
    TDEPopupMenu* m = (*it);
    delete m;
  }
  
  m_collectionMenuList.clear();
}

#include "kiviostencilsetaction.moc"
