/* run_custom_action.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2007-2021 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 "run_custom_action.hh"
#include "listermode.h"
#include "worker.h"
#include "wcfiletype.hh"
#include "fileentry.hh"
#include "nmspecialsourceext.hh"
#include <string>
#include <vector>
#include <algorithm>
#include "worker_locale.h"
#include "dnd.h"
#include "wconfig.h"
#include "aguix/stringgadget.h"
#include "aguix/fieldlistview.h"
#include "aguix/button.h"
#include "aguix/awindow.h"
#include "datei.h"

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

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

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

RunCustomAction::RunCustomAction() : FunctionProto(), m_customname( "" )
{
    hasConfigure = true;
    m_category = FunctionProto::CAT_FILETYPE;
}

RunCustomAction::~RunCustomAction()
{
}

RunCustomAction *RunCustomAction::duplicate() const
{
    RunCustomAction *ca = new RunCustomAction();
    ca->setCustomName( m_customname );
    return ca;
}

int RunCustomAction::run( std::shared_ptr< WPUContext > wpu, ActionMessage *msg )
{
    normalmoderuncustomaction( msg );
    return 0;
}

const char *RunCustomAction::getDescription()
{
    return catalog.getLocale( 1294 );
}

void RunCustomAction::normalmoderuncustomaction( ActionMessage *am )
{
    ListerMode *lm1;
    ActionMessage amsg( am->getWorker() );
    Lister *l1;
    const FileEntry *fe = NULL;
    
    switch ( am->mode ) {
      case ActionMessage::AM_MODE_DNDACTION:
          l1 = am->dndmsg->getSourceLister();
          if ( l1 == NULL ) return;
          
          fe = am->dndmsg->getFE();
          if ( fe != NULL ) {
              WCFiletype *ft;
              
              amsg.startLister = l1;
              amsg.mode = amsg.AM_MODE_SPECIAL;
              
              if ( am->filetype != NULL ) ft = am->filetype;
              else ft = fe->filetype;

              if ( ft == NULL ) {
                  if ( fe->isDir() == false ) ft = wconfig->getnotyettype(); // not yet checked
                  else ft = wconfig->getdirtype(); // dir
              }
              
              if ( ft != NULL ) {
                  // I need to make a copy of fe as DNDMsg->getFE returns a pointer to the actual FE
                  // setFE takes care of this at the moment
                  amsg.setFE( fe );
                  amsg.filetype = ft;
                  amsg.m_action_descr = RefCount<ActionDescr>( new RunCustomAction::RunCustomActionDescr( m_customname ) );
                  am->getWorker()->interpret( ft->getCustomActions( m_customname ).first, &amsg );
              }
          }
          break;
      case ActionMessage::AM_MODE_SPECIAL:
          fe = am->getFE();
          if ( fe != NULL ) {
              WCFiletype *ft;
              
              amsg.mode = amsg.AM_MODE_SPECIAL;
              
              if ( am->filetype != NULL ) ft = am->filetype;
              else ft = fe->filetype;
              if ( ft == NULL ) {
                  ft = wconfig->getnotyettype(); // not yet checked
              }
              if ( ft != NULL ) {
                  // FE is already a copy of the real FE so we don't need to make another copy
                  // but setFE does make a copy currently which doesn't hurt
                  amsg.setFE( fe );
                  amsg.filetype = ft;
                  amsg.m_action_descr = RefCount<ActionDescr>( new RunCustomAction::RunCustomActionDescr( m_customname ) );
                  am->getWorker()->interpret( ft->getCustomActions( m_customname ).first, &amsg );
              }
          }
          break;
      case ActionMessage::AM_MODE_ONLYACTIVE:
      default:
          l1 = am->getWorker()->getActiveLister();
          lm1 = NULL;
          if ( l1 != NULL ) {
              lm1 = l1->getActiveMode();
          }
          if ( lm1 != NULL ) {
              std::list< NM_specialsourceExt > files;
              lm1->getSelFiles( files,
                                ( am->mode == ActionMessage::AM_MODE_ONLYACTIVE ) ? ListerMode::LM_GETFILES_ONLYACTIVE :
                                ListerMode::LM_GETFILES_SELORACT,
                                false );
              WCFiletype *ft;
              
              amsg.startLister = l1;
              amsg.mode = amsg.AM_MODE_SPECIAL;
              
              if ( files.size() == 0 ) {
                  ft = wconfig->getvoidtype();
                  if ( ft != NULL ) {
                      amsg.setFE( NULL );
                      amsg.filetype = ft;
                      amsg.m_action_descr = RefCount<ActionDescr>( new RunCustomAction::RunCustomActionDescr( m_customname ) );
                      am->getWorker()->interpret( ft->getCustomActions( m_customname ).first, &amsg );
                  }
              } else {
                  for ( auto &ss1 : files ) {
                      fe = ss1.entry();
                      if ( fe != NULL ) {
                          ft = fe->filetype;
                          if ( ft == NULL ) {
                              if ( fe->isDir() == true ) ft = wconfig->getdirtype();
                              else ft = wconfig->getnotyettype();
                          }
                          if ( ft != NULL ) {
                              // NM_specialsourceExt already contains a duplicated FE so we can use
                              // it here without another copy
                              amsg.setFE( fe );
                              amsg.filetype = ft;
                              amsg.m_action_descr = RefCount<ActionDescr>( new RunCustomAction::RunCustomActionDescr( m_customname ) );
                              am->getWorker()->interpret( ft->getCustomActions( m_customname ).first, &amsg );
                          }
                      }
                  }
              }
          }
          break;
    }
}

int RunCustomAction::configure()
{
    AGUIX *aguix = Worker::getAGUIX();
    AWindow *win;
    StringGadget *sg;
    AGMessage *msg;
    int endmode = -1;
    char *tstr;
  
    tstr = (char*)_allocsafe( strlen( catalog.getLocale( 293 ) ) +
                              strlen( catalog.getLocale( 1245 ) ) + 1 );
    sprintf( tstr, catalog.getLocale( 293 ), catalog.getLocale( 1245 ) );
    win = new AWindow( aguix, 10, 10, 10, 10, tstr, AWindow::AWINDOW_DIALOG );
    win->create();
    _freesafe( tstr );

    AContainer *ac1 = win->setContainer( new AContainer( win, 1, 4 ), true );
    ac1->setMinSpace( 5 );
    ac1->setMaxSpace( 5 );
    
    AContainer *ac1_2 = ac1->add( new AContainer( win, 2, 1 ), 0, 0 );
    ac1_2->setMinSpace( 5 );
    ac1_2->setMaxSpace( 5 );
    ac1_2->setBorderWidth( 0 );
    ac1_2->add( new Text( aguix, 0, 0, catalog.getLocale( 779 ) ), 0, 0, AContainer::CO_FIX );

    sg = (StringGadget*)ac1_2->add( new StringGadget( aguix, 0, 0, 100, "", 0 ), 1, 0, AContainer::CO_INCW );
    sg->setText( m_customname.c_str() );
    
    ac1->add( new Text( aguix, 0, 0, catalog.getLocale( 776 ) ), 0, 1, AContainer::CO_INCWNR );

    FieldListView *name_lv = (FieldListView*)ac1->add( new FieldListView( aguix,
                                                                          0,
                                                                          0,
                                                                          100,
                                                                          10 * aguix->getCharHeight(),
                                                                          0 ), 0, 2, AContainer::CO_MIN );
    name_lv->setHBarState(2);
    name_lv->setVBarState(2);
    name_lv->setNrOfFields( 3 );
    name_lv->setFieldWidth( 1, 1 );
    
    std::vector<std::string> custom_names;
    wconfig->getAllCustomNames( custom_names );
    
    std::sort( custom_names.begin(), custom_names.end() );
    
    for ( std::vector<std::string>::const_iterator it1 = custom_names.begin();
          it1 != custom_names.end();
          it1++ ) {
        int trow = name_lv->addRow();
        name_lv->setPreColors( trow, FieldListView::PRECOLOR_ONLYACTIVE );
        name_lv->setText( trow, 0, *it1 );
    }
    
    AContainer *ac1_1 = ac1->add( new AContainer( win, 2, 1 ), 0, 3 );
    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, AContainer::CO_FIX );
    Button *cb = (Button*)ac1_1->add( new Button( aguix,
                                                  0,
                                                  0,
                                                  catalog.getLocale( 8 ),
                                                  0 ), 1, 0, AContainer::CO_FIX );
    
    win->setDoTabCycling( true );
    win->contMaximize( true );
    win->show();
    for(;endmode==-1;) {
        msg=aguix->WaitMessage(win);
        if(msg!=NULL) {
            switch(msg->type) {
              case AG_CLOSEWINDOW:
                  if(msg->closewindow.window==win->getWindow()) endmode=1;
                  break;
              case AG_BUTTONCLICKED:
                  if(msg->button.button==okb) endmode=0;
                  else if(msg->button.button==cb) endmode=1;
                  break;
              case AG_FIELDLV_ONESELECT:
                  if ( msg->fieldlv.lv == name_lv ) {
                      if ( name_lv->isValidRow( msg->fieldlv.row ) == true ) {
                          std::string s1 = name_lv->getText( msg->fieldlv.row, 0 );
                          sg->setText( s1.c_str() );
                      }
                  }
                  break;
                case AG_KEYPRESSED:
                    if ( win->isParent( msg->key.window, false ) == true ) {
                        switch ( msg->key.key ) {
                            case XK_Escape:
                                endmode = 1;
                                break;
                        }
                    }
                    break;
            }
            aguix->ReplyMessage(msg);
        }
    }
    
    if(endmode==0) {
        // ok
        setCustomName( sg->getText() );
    }
    
    delete win;
    
    return endmode;
}

bool RunCustomAction::save( Datei *fh )
{
    if ( fh == NULL ) return false;
  
    fh->configPutPairString( "customname", m_customname.c_str() );
    return true;
}

std::string RunCustomAction::getCustomName() const
{
    return m_customname;
}

void RunCustomAction::setCustomName( const std::string &newname )
{
    m_customname = newname;
}

RunCustomAction::RunCustomActionDescr::RunCustomActionDescr( const std::string &customname ) : m_customname( customname )
{
}

command_list_t RunCustomAction::RunCustomActionDescr::get_action_list( WCFiletype *ft ) const
{
    if ( ft == NULL ) return {};
    return ft->getCustomActions( m_customname ).first;
}
