/* This file is part of the KDE project
   Copyright (C) 2004-2005 Peter Simonsson <psn@linux.se>,

   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 "kivioaddstencilsetpanel.h"

#include <tqfile.h>
#include <tqdir.h>
#include <tqstringlist.h>
#include <tqiconview.h>
#include <tqgroupbox.h>
#include <tqpushbutton.h>
#include <tqtextbrowser.h>
#include <tqsplitter.h>

#include <kstandarddirs.h>
#include <tdeglobal.h>
#include <tdelistview.h>

#include "kivio_stencil_spawner_set.h"
#include "kivio_stencil_spawner.h"
#include "kivio_stencil_spawner_info.h"
#include "kivio_stencil.h"
#include "kivioglobal.h"

namespace Kivio {
  AddStencilSetPanel::AddStencilSetPanel(TQWidget *parent, const char *name)
    : KivioStencilSetWidget(parent, name)
  {
    int height = m_stencilsetGBox->height() / 2;
    TQValueList<int> sizes;
    sizes << height << height;
    m_stencilSetSplitter->setSizes(sizes);
    updateList();

    connect(m_stencilSetLView, TQ_SIGNAL(selectionChanged(TQListViewItem*)), this, TQ_SLOT(changeStencilSet(TQListViewItem*)));
    connect(m_addToDocBtn, TQ_SIGNAL(clicked()), this, TQ_SLOT(addToDocument()));

    TQListViewItem* tmp = m_stencilSetLView->firstChild();

    if(tmp) {
      tmp = tmp->firstChild();

      if(tmp) {
        m_stencilSetLView->setSelected(tmp, true);
        m_stencilSetLView->ensureItemVisible(tmp);
      }
    }
    m_stencilSetLView-> setShadeSortColumn(false);
  }
  
  
  AddStencilSetPanel::~AddStencilSetPanel()
  {
  }
  
  void AddStencilSetPanel::updateList()
  {
    TDEStandardDirs *dirs = TDEGlobal::dirs();
    TQStringList dirList = dirs->findDirs("data", "kivio/stencils");
    dirList.sort();
    m_stencilSetLView->clear();
    
    for(TQStringList::Iterator it = dirList.begin(); it != dirList.end(); ++it)
    {
      TQString dir = (*it);
      loadCollections(dir);
    }
  }

  void AddStencilSetPanel::loadCollections(const TQString& dir)
  {
    TQDir rootDir( dir );
  
    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());
        TQListViewItem* li = m_stencilSetLView->firstChild();
        
        while(li) {
          if(li->text(1) == cId) {
            break;
          }
          
          li = li->nextSibling();
        }
        
        if(!li) {
          li = new TDEListViewItem(m_stencilSetLView,
            KivioStencilSpawnerSet::readTitle(colFInfo->absFilePath()),
            KivioStencilSpawnerSet::readId(colFInfo->absFilePath()));
          li->setPixmap(0, loadIcon("icon", colFInfo->absFilePath()));
        }
        
        loadStencilSet(li, dir + "/" + colFInfo->fileName());
      }
      
      ++colIt;
    }
  }
  
  void AddStencilSetPanel::loadStencilSet(TQListViewItem* li, const TQString& dir)
  {
    TQDir rootDir( dir );
  
    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() != "." )
      {
        TDEListViewItem* tmp = new TDEListViewItem(li, KivioStencilSpawnerSet::readTitle(setFInfo->absFilePath()),
          dir + "/" + setFInfo->fileName());
        tmp->setPixmap(0, loadIcon("icon", setFInfo->absFilePath()));

        if(m_currentDir == setFInfo->absFilePath()) {
          tmp->setSelected(true);
          m_stencilSetLView->ensureItemVisible(tmp);
        }
      }

      ++setIt;
    }
  }

  TQPixmap AddStencilSetPanel::loadIcon(const TQString& name, const TQString& dir)
  {
    TQString fs;

    if( TQFile::exists(dir + "/" + name + ".xpm") ) {
      fs = dir + "/" + name + ".xpm";
    } else if( TQFile::exists(dir + "/" + name + ".png") ) {
      fs = dir + "/" + name + ".png";
    } else {
      return TQPixmap();
    }

    return TQPixmap( fs );
  }

  void AddStencilSetPanel::changeStencilSet(TQListViewItem* li)
  {
    if(!li || !li->parent()) {
      return;
    }
    
    m_stencilsetGBox->setTitle(li->text(0));
    m_addToDocBtn->setEnabled(true);
    KivioStencilSpawnerSet* spawnerSet = new KivioStencilSpawnerSet(li->text(0));
    // Load the stencil icons
    m_currentDir = li->text(1);
    spawnerSet->loadDir(m_currentDir);
    TQStringList files = spawnerSet->files();

    // Remove the old icons
    m_stencilIView->clear();
    KivioStencilSpawner* spawner = 0;
    KivioStencil* stencil = 0;
    int count = 0;

    for(TQStringList::Iterator it = files.begin(); it != files.end(); ++it)
    {
      spawner = spawnerSet->loadFile(m_currentDir + "/" + (*it));

      if(spawner) {
        stencil = spawner->newStencil();

        if(stencil) {
          (void) new TQIconViewItem(m_stencilIView, spawner->info()->title(), Kivio::generatePixmapFromStencil(32, 32, stencil));
          delete stencil;
          count++;
        }
      }

      if(count == 10) { // Limit to max 10 stencils
        break;
      }
    }

    m_descriptionBrowser->setText(KivioStencilSpawnerSet::readDescription(m_currentDir));

    delete spawnerSet;
  }

  void AddStencilSetPanel::addToDocument()
  {
    if(m_currentDir.isEmpty()) {
      return;
    }
    
    emit addStencilSet(m_currentDir);
  }
}

#include "kivioaddstencilsetpanel.moc"
