//==============================================
//  copyright            : (C) 2003-2005 by Will Stokes
//==============================================
//  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.
//==============================================

//Systemwide includes
#include <qwidget.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qfont.h>
#include <qpixmap.h>
#include <qapplication.h>
#include <qtoolbutton.h>
#include <qtooltip.h>

//Projectwide includes
#include "subalbumsWidget.h"
#include "subalbumPreviewWidget.h"
#include "subalbumsIconView.h"
#include "layoutWidget.h"
#include "window.h"
#include "titleWidget.h"
#include "dialogs/questionDialog.h"
#include "../config.h"
#include "../backend/album.h"
#include "../backend/subalbum.h"
#include "../backend/tools/guiTools.h"
#include "../configuration/configuration.h"

//==============================================
SubalbumsWidget::SubalbumsWidget(QWidget *parent,
                                 const char* name ) :
                                 QWidget(parent,name)
{
  //set layout pointer
  layout = (LayoutWidget*)parent;

  //create "Collections:" header
  QLabel* collectionsHeader = new QLabel( this );
  collectionsHeader->setText( tr("Collections:") );
  QFont labelFont = collectionsHeader->font();
  labelFont.setWeight(QFont::Bold);
  collectionsHeader->setFont( labelFont );
  //--------------------------------------
  //create collections list
  collections = new SubalbumsIconView( this );

  //only one item can be selected at a time
  collections->setSelectionMode( QIconView::Single ) ;

  //single column of items
  collections->setGridX(1);

  //text is on right of icons
  collections->setItemTextPos( QIconView::Right );

  //disable frame
  collections->setFrameShape ( QFrame::NoFrame );

  collections->setMaxItemWidth(500);
  collections->setPaletteBackgroundColor( QColor(193, 210, 238) );
  collections->setDragAutoScroll(true);
  collections->setAcceptDrops(true);
  collections->setVScrollBarMode( QScrollView::Auto );
  collections->setHScrollBarMode( QScrollView::Auto );
  //--------------------------------------
  //no selection by default
  currentSelection = NULL;
  //--------------------------------------
  //connect drop event on iconview to reorder slot
  connect( collections, SIGNAL(itemHasMoved()), SLOT(reorder()) );

  //handle selection attempts
  connect( collections, SIGNAL(selectionChanged(QIconViewItem*)),
           this,      SLOT(handleSelectionAttempt(QIconViewItem*)));
  //--------------------------------------
  //create create/delete buttons
  QFont buttonFont( qApp->font() );
  buttonFont.setBold(true);
  buttonFont.setPointSize( 11 );

  createButton = new QToolButton( this );
  createButton->setTextLabel(tr("Create"));
  createButton->setIconSet( QPixmap(QString(IMAGE_PATH)+"buttonIcons/create.png") );
  createButton->setTextPosition(QToolButton::Right);
  createButton->setFont( buttonFont );
  createButton->setUsesTextLabel( true );
  createButton->setEnabled(true);
  createButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
  QToolTip::add( createButton, tr("Create a collection and append to subalbum list") );
  connect( createButton, SIGNAL(clicked()), SLOT(createAction()) );
  
  deleteButton = new QToolButton( this );
  deleteButton->setTextLabel(tr("Delete"));
  deleteButton->setIconSet( QPixmap(QString(IMAGE_PATH)+"buttonIcons/delete.png") );
  deleteButton->setTextPosition(QToolButton::Right);
  deleteButton->setFont( buttonFont );
  deleteButton->setUsesTextLabel( true );
  deleteButton->setEnabled(false);
  deleteButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
  QToolTip::add( deleteButton, tr("Delete selected collection and all its contents") );
  connect( deleteButton, SIGNAL(clicked()), SLOT(deleteAction()) );
  //--------------------------------------
  //place label, listbox, and buttons in grid
  QGridLayout* grid = new QGridLayout( this, 3, 2, 0 );
  grid->addMultiCellWidget( collectionsHeader, 0, 0, 0, 1, Qt::AlignHCenter );
  grid->addMultiCellWidget( collections, 1, 1, 0, 1 );
  grid->addWidget( createButton, 2, 0, Qt::AlignHCenter);
  grid->addWidget( deleteButton, 2, 1, Qt::AlignHCenter);

  //allow collections listing to grow
  grid->setRowStretch( 1, 1 );

  //set the background of the widget to be white
  setPaletteBackgroundColor( QColor(193, 210, 238) );
}
//==============================================
void SubalbumsWidget::createAction()
{
  //create new collection object
  Album* albm = layout->getWindow()->getTitle()->getAlbum();
  Subalbum* newCollection = new Subalbum( albm, albm->getNumSubalbums()+1 );
  albm->appendSubalbum( newCollection );

  //create collection icon and auto select it
  SubalbumPreviewWidget* newCollectionIcon = new SubalbumPreviewWidget( collections, newCollection );
  newCollectionIcon->setDropEnabled(true);
  selectCollection( newCollectionIcon );
  
  //update enabled state of delete collection button
  deleteButton->setEnabled( collections->count() > 1 );
}
//==============================================
void SubalbumsWidget::deleteAction()
{
  //if an item is selected it remove it
  if(collections->currentItem() != NULL)
  {
    //if user has chosen to not receive destructive action warnings, or agrees to the action, then
    //delete subalbum and refresh view
    bool proceed = !((Window*)qApp->mainWidget())->getConfig()->getBool( "alerts", "showDestructiveAlerts" );
    if(!proceed)
    {
      QuestionDialog sure( tr("Delete collection?"),
                           tr("Once deleted a collection and it's contents cannot be brought back unless a saved copy of the album exists."),
                           "alertIcons/warning.png",
                           this );
      proceed = sure.exec();
    }
    if(proceed)
    {
      //get handle on currently selected collection
      QIconViewItem* oldSelection = collections->currentItem();

      //get handle on the next automatically selected collection
      //auto select the new collection. If there is no next 
      //collection, select the previous collection (again if present)
      QIconViewItem* newSelection = oldSelection->nextItem();
      if(newSelection == NULL) newSelection = oldSelection->prevItem();

      //auto select a remaining collection if one exists
      //we select before removing and deleting the old collection so that
      //the collection information above smoothly transitions
      selectCollection( newSelection );

      //remove the collection from the album
      Subalbum* s = ((SubalbumPreviewWidget*) oldSelection)->getSubalbum();
      layout->getWindow()->getTitle()->getAlbum()->removeSubalbum( s );

      //free the collection icon
      delete oldSelection;
      oldSelection = NULL;

      //rearrange the items in the grid, making 
      //sure  new selection is visible
      collections->arrangeItemsInGrid();
      if(newSelection != NULL) collections->ensureItemVisible( newSelection );

      //update enabled state of delete collection button
      deleteButton->setEnabled( collections->count() > 1 );

      //notifty title widget that the album's photo count has possible changed
      layout->getWindow()->getTitle()->updateMenus();
    }
  }
}
//==============================================
void SubalbumsWidget::refreshSelectedCollectionName()
{
  if( currentSelection != NULL)
    currentSelection->setText( ((SubalbumPreviewWidget*)currentSelection)->getSubalbum()->getName() );
}
//==============================================
void SubalbumsWidget::updatedSelectedCollectionImage( QPixmap* val)
{
  if( currentSelection != NULL) 
    currentSelection->setPixmap( *val );
}
//==============================================
void SubalbumsWidget::reorder()
{
  //so item has been moved, reorder linked list of items as necessary
  collections->sort( true );
  collections->arrangeItemsInGrid();

  //sync lists
  Album* albm = layout->getWindow()->getTitle()->getAlbum();
  albm->syncSubalbumList((SubalbumPreviewWidget*)collections->firstItem());
}
//==============================================
void SubalbumsWidget::updateButtons(bool enable)
{
  if(enable)
  {
    createButton->setEnabled( true );    
    deleteButton->setEnabled( buttonsState );
  }
  else
  {
    buttonsState = createButton->isEnabled();
    createButton->setEnabled( false );
    deleteButton->setEnabled( false );
  }
}
//==============================================
LayoutWidget* SubalbumsWidget::getParent() { return layout; }
QIconViewItem* SubalbumsWidget::getCurrentSelection() { return currentSelection; }
//==============================================
Subalbum* SubalbumsWidget::getSelectedSubalbum()
{ 
  return ((SubalbumPreviewWidget*) currentSelection )->getSubalbum(); 
}
//==============================================
void SubalbumsWidget::refreshCollectionsList()
{
  //delete all previous entries
  QIconViewItem* current = collections->firstItem();
  while(current != NULL)
  {
    QIconViewItem* next = current->nextItem();
    delete current;
    current = next;
  }
  
  //for some reason scrollbar does not disappear automatically.
  //Calling clear fixes this.
  collections->clear();
  
  //reset cached selection handle
  currentSelection = NULL;
  
  //insert all collections
  Subalbum* curCollection = layout->getWindow()->getTitle()->getAlbum()->getFirstSubalbum();
  while( curCollection != NULL)
  {
    SubalbumPreviewWidget* item = new SubalbumPreviewWidget( collections, curCollection );
    item->setDropEnabled(true);
    curCollection = curCollection->getNext();
  }
  
  //refresh iconview
  collections->arrangeItemsInGrid();
  
  //auto select first item
  selectFirstCollection();
}
//==============================================
void SubalbumsWidget::handleSelectionAttempt( QIconViewItem* item )
{
  //select collections only when program is not busy.
  if( !layout->getWindow()->getTitle()->getBusy() )
    selectCollection( item );
}
//==============================================
void SubalbumsWidget::selectFirstCollection()
{
  selectCollection( collections->firstItem() );
}
//==============================================
void SubalbumsWidget::selectCollection( QIconViewItem* item )
{
  //no necessary action when selecting the currently selection collection
  if(currentSelection == item) return;

  //select item
  if( item != NULL ) collections->setSelected( item, true);
  
  //cachce selection
  currentSelection = item;
  
  //emit signal that a different collection has been selected
  if(currentSelection == NULL )
    emit collectionSelected( NULL );
  else
    emit collectionSelected( ((SubalbumPreviewWidget*)currentSelection)->getSubalbum() );
}
//==============================================
/*
 void SubalbumsWidget::setSelectedSubalbum( Subalbum* selection )
{
  QIconViewItem* current = collections->firstItem();
  while(current != NULL)
  {
    //found indicated collection
    if( ((SubalbumPreviewWidget*)current)->getSubalbum() == selection )
    {
      current->setSelected( true );
      break;
    }

    //move to next item
    current = current->nextItem();
  }
}*/
//==============================================

