/* deleteop.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2001-2023 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * 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.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "listermode.h"
#include "worker.h"
#include "deleteop.h"
#include "nmspecialsourceext.hh"
#include "worker_locale.h"
#include "aguix/button.h"
#include "aguix/choosebutton.h"
#include "aguix/solidbutton.h"
#include "datei.h"
#include "deleteorder.hh"
#include "virtualdirmode.hh"

#define DELETEOPWIN_REDRAW_RATE 25.0

const char *DeleteOp::name="DeleteOp";

DeleteOp::DeleteOp() : FunctionProto()
{
  also_active = false;
  hasConfigure = true;
    m_category = FunctionProto::CAT_FILEOPS;
}

DeleteOp::~DeleteOp()
{
}

DeleteOp*
DeleteOp::duplicate() const
{
  DeleteOp *ta=new DeleteOp();
  ta->also_active = also_active;
  return ta;
}

bool
DeleteOp::isName(const char *str)
{
  if(strcmp(str,name)==0) return true; else return false;
}

const char *
DeleteOp::getName()
{
  return name;
}

int
DeleteOp::run( std::shared_ptr< WPUContext > wpu, ActionMessage *msg )
{
  ListerMode *lm1;
  if(msg->mode!=msg->AM_MODE_DNDACTION) {
    Lister *l1 = msg->getWorker()->getActiveLister();
    if(l1!=NULL) {
      startlister=l1;
      lm1=startlister->getActiveMode();
      if(lm1!=NULL) {
          if(dynamic_cast< VirtualDirMode * >( lm1 ) ) {
              normalmodedelete( msg );
          } else {
              lm1->not_supported();
          }
      }
    }
  }
  return 0;
}

const char *
DeleteOp::getDescription()
{
  return catalog.getLocale(1266);
}

int
DeleteOp::normalmodedelete( ActionMessage *am )
{
    struct deleteorder delorder;
    ListerMode *lm1 = NULL;
    VirtualDirMode *vdm = nullptr;
    NM_specialsourceExt *specialsource = NULL;
  
    if ( startlister == NULL ) return 1;
    lm1 = startlister->getActiveMode();

    if ( lm1 == NULL ) return 1;

    vdm = dynamic_cast< VirtualDirMode * >( lm1 );
  
    if ( am->mode == am->AM_MODE_NORMAL ) {
        memset( &delorder, 0, sizeof( delorder ) );
        if ( also_active == true ) {
            delorder.source = delorder.NM_ALLENTRIES;
        } else {
            delorder.source = delorder.NM_ONLYSELECTED;
        }

        delorder.delmode = delorder.NM_DELMODE_NORMAL;
        delorder.dirdel = delorder.NM_DIRDELETE_NORMAL;

        delorder.dowin = new DeleteOpWin( Worker::getAGUIX() );

        if ( vdm ) {
            vdm->deletef( &delorder );
        }

        delete delorder.dowin;

        if ( delorder.source == delorder.NM_SPECIAL ) {
            if ( specialsource != NULL ) delete specialsource;
            delete delorder.sources;
        }
    }
    return 0;
}

int DeleteOp::configure()
{
  ChooseButton *cb;
  AGUIX *aguix = Worker::getAGUIX();
  AWindow *win;
  char *tstr;
  const int cincw = AContainer::ACONT_MINH +
                    AContainer::ACONT_MINW +
                    AContainer::ACONT_MAXH;
  const int cincwnr = cincw +
                      AContainer::ACONT_NORESIZE;
  const int cfix = AContainer::ACONT_MINH +
                   AContainer::ACONT_MINW +
                   AContainer::ACONT_MAXH +
                   AContainer::ACONT_MAXW;

  tstr=(char*)_allocsafe(strlen(catalog.getLocale(293))+strlen(getDescription())+1);
  sprintf(tstr,catalog.getLocale(293),getDescription());
  win = new AWindow( aguix, 10, 10, 10, 10, tstr, AWindow::AWINDOW_DIALOG );
  win->create();
  _freesafe(tstr);
  
  AContainer *ac1 = win->setContainer( new AContainer( win, 1, 2 ), true );
  ac1->setMinSpace( 5 );
  ac1->setMaxSpace( 5 );

  cb = (ChooseButton*)ac1->add( new ChooseButton( aguix, 0, 0, 20, 20, ( also_active == true ) ? 1 : 0,
						  catalog.getLocale( 153 ), LABEL_RIGHT, 0 ), 0, 0, cincwnr );
  
  AContainer *ac1_1 = ac1->add( new AContainer( win, 2, 1 ), 0, 1 );
  ac1_1->setMinSpace( 5 );
  ac1_1->setMaxSpace( -1 );
  ac1_1->setBorderWidth( 0 );
  Button *okb =(Button*)ac1_1->add( new Button( aguix,
                                                0,
                                                0,
                                                catalog.getLocale( 11 ),
                                                0 ), 0, 0, cfix );
  Button *cancelb = (Button*)ac1_1->add( new Button( aguix,
						     0,
						     0,
						     catalog.getLocale( 8 ),
						     0 ), 1, 0, cfix );

  win->setDoTabCycling( true );
  win->contMaximize( true );
  win->show();
  AGMessage *msg;
  while((msg=aguix->GetMessage(NULL))!=NULL) aguix->ReplyMessage(msg);
  int ende=0;
  while(ende==0) {
    msg=aguix->WaitMessage(win);
    if(msg!=NULL) {
      if(msg->type==AG_CLOSEWINDOW) {
        if(msg->closewindow.window==win->getWindow()) ende=-1;
      } else if(msg->type==AG_BUTTONCLICKED) {
        if(msg->button.button==okb) ende=1;
        else if(msg->button.button==cancelb) ende=-1;
      } else if ( msg->type == AG_KEYPRESSED ) {
          if ( win->isParent( msg->key.window, false ) == true ) {
              switch ( msg->key.key ) {
                  case XK_Escape:
                      ende = -1;
                      break;
              }
          }
      }
      aguix->ReplyMessage(msg);
    }
  }
  if(ende==1) {
    also_active = cb->getState();
  }
  delete win;
  return (ende==1)?0:1;
}

bool DeleteOp::save(Datei *fh)
{
  if ( fh == NULL ) return false;
  fh->configPutPairBool( "alsoactive", also_active );
  return true;
}

void DeleteOp::setAlsoActive( bool nv )
{
  also_active = nv;
}

/*********************
 * Class DeleteOpWin *
 *********************/

DeleteOpWin::DeleteOpWin(AGUIX*taguix)
{
  this->aguix=taguix;
  source=dupstring("");
  deleted_files=0;
  files=0;
  deleted_dirs=0;
  dirs=0;
  
  window=NULL;
  melw = 0;
  filenamespace = 0;
  ismessage = false;

  update_sourcetext = false;
  update_files2gotext = false;
  update_dirs2gotext = false;
  
  lencalc = new AFontWidth( aguix, NULL );
}

DeleteOpWin::~DeleteOpWin()
{
  if(source!=NULL) _freesafe(source);
  if(window!=NULL) close();
  delete lencalc;
}

int
DeleteOpWin::open()
{
  int w,h;
  int tx,ty;
  Text *ttext;

  close();
  w=400;
  h=10;
  window = new AWindow( aguix, 10, 10, w, h, catalog.getLocale( 1266 ),
                        AWindow::AWINDOW_DIALOG );
  window->create();
  tx=5;
  ty=5;
  sourcetext=(Text*)window->add(new Text(aguix,tx,ty,""));
  ismessage = true;
  ty+=sourcetext->getHeight()+5;
  bb1=(BevelBox*)window->add(new BevelBox(aguix,tx,ty,w-2*tx,2,0));
  ty+=bb1->getHeight()+5;

  ttext=(Text*)window->add(new Text(aguix,tx,ty,catalog.getLocale(142)));
  tx+=ttext->getWidth()+5;
  files2gotext=(Text*)window->add(new Text(aguix,tx,ty,""));
  tx=5;
  ty+=ttext->getHeight()+5;
  ttext=(Text*)window->add(new Text(aguix,tx,ty,catalog.getLocale(143)));
  tx+=ttext->getWidth()+5;
  dirs2gotext=(Text*)window->add(new Text(aguix,tx,ty,""));
  tx=5;
  ty+=ttext->getHeight()+5;

  gsb=(SolidButton*)window->add(new SolidButton(aguix,tx+1,ty+1,w-2*(tx+1),"","button-special1-fg", "button-special1-bg",0));
  bb2=(BevelBox*)window->add(new BevelBox(aguix,tx,ty,w-2*tx,gsb->getHeight()+2,1));
  gsb->toFront();
  sbw=gsb->getWidth();
  ty+=bb2->getHeight()+5;

  bb3=(BevelBox*)window->add(new BevelBox(aguix,tx,ty,w-2*tx,2,0));
  ty+=bb3->getHeight()+5;
  cb = (Button*)window->add( new Button( aguix, tx, ty,
					 catalog.getLocale( 8 ), 0 ) );
  cb->move(w/2-cb->getWidth()/2,cb->getY());
  ty+=cb->getHeight()+5;
  h=ty;
  window->setDoTabCycling( true );
  window->resize(w,h);
  window->setMinSize(w,h);
  //window->setMaxSize(w,h);
  window->centerScreen();
  window->show();

  filenamespace = w - window->getBorderWidth() - sourcetext->getX();
  filenamespace -= aguix->getTextWidth( catalog.getLocale( 141 ) ) - 2 * aguix->getTextWidth( " " );

  return 0;
}

void
DeleteOpWin::close()
{
  if(window!=NULL) {
    delete window;
  }
  window=NULL;
}

void
DeleteOpWin::set_files_to_delete(long nfiles)
{
  if(nfiles>0) files=nfiles;
  else files=0;
  update_files2gotext=true;
}

void
DeleteOpWin::set_dirs_to_delete(long ndirs)
{
  if(ndirs>0) dirs=ndirs;
  else dirs=0;
  update_dirs2gotext=true;
}

void
DeleteOpWin::dir_finished()
{
  deleted_dirs++;
  update_dirs2gotext=true;
}

void
DeleteOpWin::file_finished()
{
  // inc counter
  deleted_files++;
  update_files2gotext=true;
}

void
DeleteOpWin::setfilename(char *name)
{
  if(source!=NULL) _freesafe(source);
  if(name!=NULL)
    source=dupstring(name);
  else
    source=dupstring("");
  update_sourcetext=true;
  ismessage = false;
}

int
DeleteOpWin::redraw()
{ /* this functions will redraw the window AND process events for this window
   * returns values:
   *  0 for regular exit
   *  1 when clicked Cancel-Button or closed window
   *  other not implemented */
  int returnvalue=0;
  char tstr[1024];
  float rate;
  bool updategsb=false;
  int tw;
  bool doresize = false;
  struct timeval now;
  double diff;
  bool allow_update = false;
    
  gettimeofday( &now, NULL );
  diff = now.tv_sec + now.tv_usec / 1000000.0;
  diff -= (double)m_last_update_time.tv_sec + m_last_update_time.tv_usec / 1000000.0;
  if ( diff >= ( 1.0 / DELETEOPWIN_REDRAW_RATE ) ) {
      m_last_update_time = now;
      allow_update = true;
  }

  if ( ( update_sourcetext == true ) && ( ismessage == false ) && allow_update ) {
    if ( source != NULL ) {
        auto shrinked_source = m_fns.shrink( source, filenamespace, *lencalc );
        sourcetext->setText( AGUIXUtils::formatStringToString( catalog.getLocale( 141 ), shrinked_source.c_str() ).c_str() );
    } else {
        sourcetext->setText( AGUIXUtils::formatStringToString( catalog.getLocale( 141 ), "" ).c_str() );
    }
    /* no need for explicit redraw */
    update_sourcetext=false;
  }
  if(update_files2gotext==true && allow_update) {
    sprintf(tstr,"%ld",files-deleted_files);
    files2gotext->setText(tstr);

    tw = files2gotext->getX() + files2gotext->getWidth() + window->getBorderWidth();
    if ( tw > melw ) {
      melw = tw;
      doresize = true;
    }

    update_files2gotext=false;
    updategsb=true;
  }
  if(update_dirs2gotext==true && allow_update) {
    sprintf(tstr,"%ld",dirs-deleted_dirs);
    dirs2gotext->setText(tstr);

    tw = dirs2gotext->getX() + dirs2gotext->getWidth() + window->getBorderWidth();
    if ( tw > melw ) {
      melw = tw;
      doresize = true;
    }

    update_dirs2gotext=false;
    updategsb=true;
  }
  if(updategsb==true && allow_update) {
    if((files+dirs)>0)
      rate=(float)(deleted_files+deleted_dirs)/(float)(files+dirs);
    else
      rate=0.0;
    if  ( rate < 0.01 )
      rate = 0.0;
    sprintf(tstr,"%.4g %%",rate*100);
    gsb->setText(tstr);
    gsb->resize( w_max( (int)( sbw * rate ), 2 ), gsb->getHeight() );
  }
  
  if ( doresize == true ) {
    // only resize if window is smaller
    if ( window->getWidth() < melw ) {
      window->resize ( melw,  window->getHeight() );
    }
    // anyway the min size has changed so set it again
    window->setMinSize( melw, bb3->getY() + bb3->getHeight() + 5 +
                              cb->getHeight() + window->getBorderWidth() );
  }
  
  //window->redraw();
  aguix->Flush();
  /* update complete
     now check for X-messages */
  AGMessage *msg;
  do {
    msg=aguix->GetMessage( window );
    if(msg!=NULL) {
      switch(msg->type) {
        case AG_CLOSEWINDOW:
          if(msg->closewindow.window==window->getWindow()) returnvalue=1;
          break;
        case AG_BUTTONCLICKED:
          if(msg->button.button==cb) returnvalue=1;
          break;
	case AG_KEYPRESSED:
	  if ( msg->key.key == XK_Escape ) {
	    std::string b1 = catalog.getLocale( 667 );
	    b1 += "|";
	    b1 += catalog.getLocale( 668 );
	    if ( request( catalog.getLocale( 123 ), catalog.getLocale( 666 ), b1.c_str(), Requester::REQUEST_NONE ) == 0 ) {
	      returnvalue = 1;
	    }
	  }
	  break;
        case AG_SIZECHANGED:
          if ( msg->size.window == window->getWindow() ) {
            bb1->resize( msg->size.neww - 2 * window->getBorderWidth(), bb1->getHeight() );
            sbw = bb1->getWidth() - 2;
            bb2->resize( msg->size.neww - 2 * window->getBorderWidth(), bb2->getHeight() );
            bb3->resize( msg->size.neww - 2 * window->getBorderWidth(), bb3->getHeight() );
            cb->move( msg->size.neww / 2 - cb->getWidth() / 2,
                      msg->size.newh - window->getBorderWidth() - cb->getHeight() );
  
            filenamespace = msg->size.neww - window->getBorderWidth() - sourcetext->getX();
            filenamespace -= aguix->getTextWidth( catalog.getLocale( 141 ) ) - 2 * aguix->getTextWidth( " " );
  
            // read copyop.cc:CopyOpWin::redraw for more comments
          }
          break;
      }
      aguix->ReplyMessage(msg);
    }
  } while(msg!=NULL);
  return returnvalue;
}

void
DeleteOpWin::setmessage( const char *msg )
{
  if(msg!=NULL) sourcetext->setText(msg);
  else sourcetext->setText("");
  ismessage = true;
}

void
DeleteOpWin::dec_file_counter(unsigned long f)
{
  files-=f;
  update_files2gotext=true;
}

void
DeleteOpWin::dec_dir_counter(unsigned long d)
{
  dirs-=d;
  update_dirs2gotext=true;
}

int DeleteOpWin::request( const char *title,
                          const char *text,
                          const char *buttons,
                          Requester::request_flags_t flags )
{
  if ( window != NULL ) {
    return window->request( title, text, buttons, flags );
  } else {
    return Worker::getRequester()->request( title, text, buttons, flags );
  }
}

int DeleteOpWin::string_request( const char *title,
                                 const char *lines,
                                 const char *default_str,
                                 const char *buttons,
                                 char **return_str,
                                 Requester::request_flags_t flags )
{
  if ( window != NULL ) {
    return window->string_request( title, lines, default_str, buttons, return_str, flags );
  } else {
    return Worker::getRequester()->string_request( title, lines, default_str, buttons, return_str, flags );
  }
}

