/* externalvdirop.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2017-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 "externalvdirop.hh"
#include "listermode.h"
#include "worker.h"
#include "ownop.h"
#include "wpucontext.h"
#include "execlass.h"
#include "worker_locale.h"
#include "aguix/button.h"
#include "aguix/stringgadget.h"
#include "aguix/awindow.h"
#include "aguix/textstorage.h"
#include "aguix/textview.h"
#include "aguix/choosebutton.h"
#include "aguix/fieldlistview.h"
#include "virtualdirmode.hh"
#include "nwc_path.hh"
#include "workerinitialsettings.hh"
#include "pers_string_list.hh"

int ExternalVDirOp::s_vdir_number = 1;

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

int ExternalVDirOp::instance_counter = 0;
size_t ExternalVDirOp::history_size = 1000;
std::unique_ptr< PersistentStringList > ExternalVDirOp::m_history;

ExternalVDirOp::ExternalVDirOp() : FunctionProto()
{
    m_command_string = "";
    m_category = FunctionProto::CAT_FILELIST;

    if ( instance_counter == 0 ) {
        initHistory();
    }
    instance_counter++;

    hasConfigure = true;
}

ExternalVDirOp::~ExternalVDirOp()
{
    instance_counter--;
    if ( instance_counter == 0 ) {
        closeHistory();
    }
}

ExternalVDirOp*
ExternalVDirOp::duplicate() const
{
    ExternalVDirOp *ta = new ExternalVDirOp();
    ta->setCommandString( m_command_string );
    ta->setRequestParameters( requestParameters() );
    return ta;
}

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

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

int ExternalVDirOp::handleOutput( Worker *w,
                                  const std::string &basedir,
                                  const std::string &output )
{
    std::vector< std::string > lines;

    std::string name = AGUIXUtils::formatStringToString( "extvdir%d", s_vdir_number++ );

    if ( s_vdir_number < 0 ) {
        // avoid negative and zero number
        s_vdir_number = 1;
    }

    std::unique_ptr< NWC::Dir > vdir( new NWC::Dir( name ) );

    AGUIXUtils::split_string( lines, output, '\n' );

    for ( auto &l : lines ) {
        if ( l.empty() ) continue;

        std::string fullname;

        if ( AGUIXUtils::starts_with( l, "/" ) ) {
            fullname = l;
        } else {
            fullname = basedir;

            if ( ! AGUIXUtils::ends_with( fullname, "/" ) ) {
                fullname += "/";
            }

            fullname += l;
        }

        fullname = NWC::Path::normalize( fullname );

        NWC::FSEntry fse( fullname );
        if ( fse.entryExists() ) {
            vdir->add( fse );
        }
    }

    Lister *l1;

    l1 = w->getActiveLister();
    if ( l1 != NULL ) {
        l1->switch2Mode( 0 );

        VirtualDirMode *vdm = dynamic_cast< VirtualDirMode* >( l1->getActiveMode() );
        if ( vdm != NULL ) {
            vdm->newTab();

            vdm->showDir( vdir );
        }
    }

    return 0;
}

int
ExternalVDirOp::run( std::shared_ptr< WPUContext > wpu, ActionMessage *msg )
{
    std::string res_str;
    int res = 0;

    if ( requestParameters() == true ) {
        if ( doconfigure( 1 ) != 0 ) return 0;
    } else {
        m_t_command_string = m_command_string;
    }
  
    if ( wpu->parse( m_t_command_string.c_str(),
                     res_str,
                     a_max( EXE_STRING_LEN - 1024, 256 ),
                     true, WPUContext::PERSIST_FLAGS ) == WPUContext::PARSE_SUCCESS ) {
        int exeerror = 1;
        std::unique_ptr<ExeClass> ec( new ExeClass( msg->getWorker() ) );
        ec->cdDir( wpu->getBaseDir() );
        ec->addCommand( "%s", res_str.c_str() );
        int ret = ec->getReturnCode( &exeerror );

        if ( ret == 0 ) {
            std::string output;
            if ( ec->readOutput( output ) == 0 ) {
                res = handleOutput( msg->getWorker(),
                                    wpu->getBaseDir(),
                                    output );
            }
        } else {
            if ( Worker::getRequester() != NULL ) {
                std::string error, str1;

                auto reqstr = AGUIXUtils::formatStringToString( catalog.getLocale( 1205 ), res_str.c_str(), WEXITSTATUS( ret ) );
                
                ec->readErrorOutput( error, 1024 );
                
                str1 = reqstr;
                str1 += error;

                RefCount<AFontWidth> lencalc( new AFontWidth( Worker::getAGUIX(), NULL ) );
                auto ts = std::make_shared< TextStorageString >( str1, lencalc );

                Worker::getRequester()->request( catalog.getLocale( 347 ), ts, catalog.getLocale( 11 ) );
            }
            res = 1;
        }
    }

    return res;
}

bool
ExternalVDirOp::save(Datei *fh)
{
    if ( fh == NULL ) return false;
    fh->configPutPairString( "commandstring", m_command_string.c_str() );

    if ( requestParameters() ) {
        fh->configPutPairBool( "requestflags", requestParameters() );
    }

    return true;
}

const char *
ExternalVDirOp::getDescription()
{
    return catalog.getLocale( 1309 );
}

int
ExternalVDirOp::configure()
{
    return doconfigure(0);
}


static void show_matching_entries( const std::list< std::string > &list,
                                   const std::string &prefix,
                                   FieldListView *lv )
{
    lv->setSize( 0 );

    for ( auto &p : list ) {
        if ( ! AGUIXUtils::starts_with( p, prefix ) ) continue;

        int row = lv->insertRow( 0 );
        lv->setText( row, 0, p );
        lv->setPreColors( row, FieldListView::PRECOLOR_ONLYACTIVE );
    }

    lv->redraw();
}

int
ExternalVDirOp::doconfigure( int mode )
{
    AGUIX *aguix = Worker::getAGUIX();
    AWindow *win;
    AGMessage *msg;

    int endmode = -1;

    auto title = AGUIXUtils::formatStringToString( catalog.getLocale( 293 ),
                                                   getDescription() );
    win = new AWindow( aguix, 10, 10, 10, 10, title.c_str(), AWindow::AWINDOW_DIALOG );
    win->create();

    AContainer *ac1 = win->setContainer( new AContainer( win, 1, 5 ), true );
    ac1->setMinSpace( 5 );
    ac1->setMaxSpace( 5 );

    RefCount<AFontWidth> lencalc( new AFontWidth( aguix, NULL ) );
    auto help_ts = std::shared_ptr< TextStorageString >( new TextStorageString( catalog.getLocale( 1206 ), lencalc ) );
    TextView *help_tv = ac1->addWidget( new TextView( aguix,
                                                      0, 0, 300, 80, "", help_ts ),
                                        0, 0, AContainer::CO_INCW );
    help_tv->setLineWrap( true );
    help_tv->maximizeYLines( 10, 500 );
    help_tv->showFrame( false );
    ac1->readLimits();
    help_tv->show();
    help_tv->setAcceptFocus( false );

    TextView::ColorDef tv_cd = help_tv->getColors();
    tv_cd.setBackground( 0 );
    tv_cd.setTextColor( 1 );
    help_tv->setColors( tv_cd );

    AContainer *ac1_3 = ac1->add( new AContainer( win, 3, 1 ), 0, 1 );
    ac1_3->setMinSpace( 5 );
    ac1_3->setMaxSpace( 5 );
    ac1_3->setBorderWidth( 0 );
    ac1_3->add( new Text( aguix, 0, 0, catalog.getLocale( 1207) ), 0, 0, AContainer::CO_FIX );
    StringGadget *sgcf = ac1_3->addWidget( new StringGadget( aguix, 0, 0, 100, m_command_string.c_str(), 0 ),
                                           1, 0, AContainer::CO_INCW );
    Button *flagb = ac1_3->addWidget( new Button( aguix,
                                                  0,
                                                  0,
                                                  "F",
                                                  0 ), 2, 0, AContainer::CO_FIX );
    auto *history_lv = ac1->addWidget( new FieldListView( aguix, 0, 0, 100, 7 * aguix->getCharHeight(), 0 ), 0, 2, AContainer::CO_MIN );

    history_lv->setNrOfFields( 1 );
    history_lv->setGlobalFieldSpace( 5 );
    history_lv->setFieldText( 0, catalog.getLocale( 1565 ) );
    history_lv->setShowHeader( true );
    history_lv->setConsiderHeaderWidthForDynamicWidth( true );
    history_lv->setHBarState( 2 );
    history_lv->setVBarState( 2 );
    history_lv->setDisplayFocus( true );
    history_lv->setAcceptFocus( true );

    std::list< std::string > cur_history = m_history->getList();
    show_matching_entries( cur_history, m_command_string, history_lv );

    ChooseButton *rfcb = nullptr;
    if ( mode == 0 ) {
        rfcb = (ChooseButton*)ac1->add( new ChooseButton( aguix, 0, 0, 20, 20, ( requestParameters() == true ) ? 1 : 0,
                                                          catalog.getLocale( 294 ), LABEL_RIGHT, 0 ), 0, 3, AContainer::CO_INCWNR );
    }

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

    win->setDoTabCycling( true );
    win->show();
    sgcf->takeFocus();

    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 == cancelb ) endmode = 1;
                    else if ( msg->button.button == flagb ) {
                        char *tstr = OwnOp::getFlag();
                        if ( tstr != NULL ) {
                            sgcf->insertAtCursor( tstr );
                            _freesafe( tstr );
                        }
                    }
                    break;
                case AG_KEYPRESSED:
                    if ( win->isParent( msg->key.window, false ) == true ) {
                        switch ( msg->key.key ) {
                            case XK_Return:
                                if ( cancelb->getHasFocus() == true ) {
                                    endmode = 1;
                                } else {
                                    endmode=0;
                                }
                                break;
                            case XK_Escape:
                                endmode = 1;
                                break;
                            case XK_Down:
                                if ( sgcf->isActive() ) {
                                    history_lv->setActiveRow( 0 );
                                    history_lv->takeFocus();
                                    history_lv->showActive();
                                    sgcf->setText( history_lv->getText( 0, 0 ).c_str() );
                                }
                                break;
                        }
                    }
                    break;
                case AG_STRINGGADGET_CONTENTCHANGE:
                    if ( msg->stringgadget.sg == sgcf ) {
                        show_matching_entries( cur_history, sgcf->getText(), history_lv );
                    }
                    break;
                case AG_FIELDLV_ONESELECT:
                case AG_FIELDLV_MULTISELECT: {
                    int row = history_lv->getActiveRow();
                    if ( history_lv->isValidRow( row ) == true ) {
                        sgcf->setText( history_lv->getText( row, 0 ).c_str() );
                    }
                    break;
                }
            }
            aguix->ReplyMessage( msg );
        }
    }
  
    if ( endmode == 0 ) {
        // ok

        if ( mode == 1 ) {
            m_t_command_string = sgcf->getText();
            addHistoryItem( m_t_command_string );
        } else {
            setCommandString( sgcf->getText() );
            setRequestParameters( rfcb->getState() );
        }
    }
    delete win;

    return endmode;
}

void ExternalVDirOp::setCommandString( const std::string &str )
{
    m_command_string = str;
}

bool ExternalVDirOp::isInteractiveRun() const
{
    return true;
}

void ExternalVDirOp::setInteractiveRun()
{
    setRequestParameters( true );
}

void ExternalVDirOp::initHistory()
{
    std::string str1;

    str1 = WorkerInitialSettings::getInstance().getConfigBaseDir();
    str1 = NWC::Path::join( str1, "externalvdir-history" );

    m_history = std::unique_ptr< PersistentStringList >( new PersistentStringList( str1 ) );
}

void ExternalVDirOp::closeHistory()
{
    m_history.reset();
}

std::list< std::string > ExternalVDirOp::getHistory()
{
    if ( m_history ) {
        return m_history->getList();
    }

    std::string str1;

    str1 = WorkerInitialSettings::getInstance().getConfigBaseDir();
    str1 = NWC::Path::join( str1, "externalvdir-history" );

    auto h = std::unique_ptr< PersistentStringList >( new PersistentStringList( str1 ) );

    return h->getList();
}

void ExternalVDirOp::addHistoryItem( const std::string &str )
{
    if ( str.empty() ) return;

    if ( m_history->contains( str ) ) {
        m_history->removeEntry( str );
        m_history->pushFrontEntry( str );
    } else {
        if ( m_history->size() >= history_size ) {
            m_history->removeLast();
        }
        m_history->pushFrontEntry( str );
    }
}
