/* searchop.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2006-2024 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 "searchop.hh"
#include "listermode.h"
#include "worker.h"
#include "flagreplacer.hh"
#include "aguix/acontainerbb.h"
#include "aguix/kartei.h"
#include "aguix/stringgadget.h"
#include "aguix/choosebutton.h"
#include "aguix/button.h"
#include "worker_locale.h"
#include "wconfig.h"
#include "datei.h"
#include "searchopbg.hh"
#include "virtualdirmode.hh"

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

int SearchOp::_stored_results_ctr = 0;

#define DEFAULT_EDIT_COMMAND "{scripts}/xeditor -line {l} {f}"

SearchOp::SearchOp() : FunctionProto()
{
    _edit_command = DEFAULT_EDIT_COMMAND;
    _show_prev_results = false;
    hasConfigure = true;
    _stored_results_ctr++;
}

SearchOp::~SearchOp()
{
    _stored_results_ctr--;
    if ( _stored_results_ctr < 1 ) {
        SearchOpBG::clear_stored_results();
    }
}

SearchOp*
SearchOp::duplicate() const
{
    SearchOp *ta = new SearchOp();
    ta->setEditCommand( _edit_command );
    ta->setShowPrevResults( _show_prev_results );
    ta->setUseSelectedEntries( m_use_selected_entries );
    return ta;
}

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

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

int
SearchOp::run( std::shared_ptr< WPUContext > wpu, ActionMessage *msg )
{
    prepareWindow( msg );

    return 0;
}

int SearchOp::prepareWindow( ActionMessage *msg )
{
    AGUIX *aguix = Worker::getAGUIX();

    std::string _initial_start_dir = "/";
    std::unique_ptr< NWC::Dir > start_vdir;
  
    if ( msg->mode != msg->AM_MODE_DNDACTION ) {
        Lister *l1;
        ListerMode *lm1;
        l1 = msg->getWorker()->getActiveLister();
        if ( l1 != NULL ) {
            lm1 = l1->getActiveMode();
            if ( lm1 != NULL ) {
                VirtualDirMode *vdm = dynamic_cast< VirtualDirMode *>( lm1 );

                if ( vdm && m_use_selected_entries ) {
                    start_vdir = vdm->get_selected_entries_as_vdir( ListerMode::LM_GETFILES_ONLYSELECT );
                    if ( start_vdir && start_vdir->empty() ) {
                        start_vdir.reset();
                    }
                }

                if ( ( ! start_vdir ) &&
                     vdm && ! vdm->currentDirIsReal() ) {
                    start_vdir = vdm->getCurrentDir();
                } else {
                    if ( ! lm1->getCurrentDirectory().empty() ) {
                        _initial_start_dir = lm1->getCurrentDirectory();
                    }
                }
            }
        }
    }

    RefCount< SearchOpBG > sbg( new SearchOpBG( msg->getWorker() ) );

    sbg->setInitialVDir( std::move( start_vdir ) );
    sbg->setInitialStartDir( _initial_start_dir );
    sbg->setShowPrevResults( _show_prev_results );
    sbg->setEditCommand( _edit_command );

    sbg->createWindow();

    if ( sbg->getAWindow() != NULL ) {
	aguix->registerBGHandler( sbg->getAWindow(), sbg );
    }

    return 0;
}

const char *
SearchOp::getDescription()
{
    return catalog.getLocale( 1291 );
}

bool SearchOp::save( Datei *fh )
{
    if ( fh == NULL ) return false;
    fh->configPutPairString( "editcommand", _edit_command.c_str() );
    fh->configPutPairBool( "showprevresults", _show_prev_results );

    if ( m_use_selected_entries ) {
        fh->configPutPairBool( "useselectedentries", m_use_selected_entries );
    }

    return true;
}

int SearchOp::configure()
{
    AGUIX *aguix = Worker::getAGUIX();
    AWindow *win;
    StringGadget *sg;
    AGMessage *msg;
    int endmode=-1;

    char *tstr;
    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, 5 ), true );
    ac1->setMinSpace( 5 );
    ac1->setMaxSpace( 5 );

    AContainer *ac1_1 = ac1->add( new AContainer( win, 3, 1 ), 0, 0 );
    ac1_1->setMinSpace( 0 );
    ac1_1->setMaxSpace( 0 );
    ac1_1->setBorderWidth( 0 );

    ac1_1->add( new Text( aguix, 0, 0, catalog.getLocale( 719 ) ),
                0, 0, AContainer::CO_FIX );
    sg = (StringGadget*)ac1_1->add( new StringGadget( aguix, 0, 0, 200, _edit_command.c_str(), 0 ),
                                    1, 0, AContainer::CO_INCW );
    Button *flagb = (Button*)ac1_1->add( new Button( aguix,
                                                     0,
                                                     0,
                                                     "F",
                                                     0 ), 2, 0, AContainer::CO_FIX );
    flagb->resize( flagb->getWidth(), sg->getHeight() );
    ac1_1->readLimits();

    Button *resetb = (Button*)ac1->add( new Button( aguix,
                                                    0,
                                                    0,
                                                    catalog.getLocale( 196 ),
                                                    0 ), 0, 1, AContainer::CO_INCW );

    ChooseButton *sprcb = (ChooseButton*)ac1->add( new ChooseButton( aguix,
                                                                     0,
                                                                     0,
                                                                     _show_prev_results,
                                                                     catalog.getLocale( 746 ),
                                                                     LABEL_RIGHT, 0 ),
                                                   0, 2, AContainer::CO_INCWNR );

    ChooseButton *start_with_selected_b = (ChooseButton*)ac1->add( new ChooseButton( aguix,
                                                                                     0,
                                                                                     0,
                                                                                     m_use_selected_entries,
                                                                                     catalog.getLocale( 1558 ),
                                                                                     LABEL_RIGHT, 0 ),
                                                                   0, 3, AContainer::CO_INCWNR );

    AContainer *ac1_2 = ac1->add( new AContainer( win, 2, 1 ), 0, 4 );
    ac1_2->setMinSpace( 5 );
    ac1_2->setMaxSpace( -1 );
    ac1_2->setBorderWidth( 0 );
    Button *okb =(Button*)ac1_2->add( new Button( aguix,
                                                  0,
                                                  0,
                                                  catalog.getLocale( 11 ),
                                                  0 ), 0, 0, AContainer::CO_FIX );
    Button *cb = (Button*)ac1_2->add( new Button( aguix,
                                                  0,
                                                  0,
                                                  catalog.getLocale( 8 ),
                                                  0 ), 1, 0, AContainer::CO_FIX );
    win->setDoTabCycling( true );
    win->contMaximize( true );
    win->show();

    FlagReplacer::FlagHelp flags;

    flags.registerFlag( "{f}", catalog.getLocale( 589 ) );
    flags.registerFlag( "{F}", catalog.getLocale( 590 ) );
    flags.registerFlag( "{l}", catalog.getLocale( 718 ) );
    flags.registerFlag( "{scripts}", catalog.getLocaleFlag( 53 ) );

    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;
                    else if ( msg->button.button == flagb ) {
                        std::string str1 = FlagReplacer::requestFlag( flags );
                        if ( str1.length() > 0 ) {
                            sg->insertAtCursor( str1.c_str() );
                        }
                    } else if ( msg->button.button == resetb ) {
                        sg->setText( DEFAULT_EDIT_COMMAND );
                    }
                    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
        setEditCommand( sg->getText() );
        setShowPrevResults( sprcb->getState() );
        setUseSelectedEntries( start_with_selected_b->getState() );
    }
  
    delete win;

    return endmode;
}

void SearchOp::setEditCommand( const std::string &str )
{
    _edit_command = str;
}

void SearchOp::setShowPrevResults( bool nv )
{
    _show_prev_results = nv;
}

void SearchOp::setUseSelectedEntries( bool nv )
{
    m_use_selected_entries = nv;
}
