/* activatetextviewmodeop.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 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 "activatetextviewmodeop.hh"
#include "listermode.h"
#include "worker.h"
#include "nmspecialsourceext.hh"
#include "datei.h"
#include "aguix/button.h"
#include "aguix/choosebutton.h"
#include "aguix/cyclebutton.h"
#include "aguix/stringgadget.h"
#include "worker_locale.h"
#include "chtimeorder.hh"
#include "virtualdirmode.hh"
#include "ownop.h"
#include "wconfig.h"

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

ActivateTextViewModeOp::ActivateTextViewModeOp() : FunctionProto()
{
    hasConfigure = true;
    m_category = FunctionProto::CAT_OTHER;
}

ActivateTextViewModeOp::~ActivateTextViewModeOp()
{
}

ActivateTextViewModeOp* ActivateTextViewModeOp::duplicate() const
{
    ActivateTextViewModeOp *ta = new ActivateTextViewModeOp();

    ta->m_active_side = m_active_side;
    ta->m_source_mode = m_source_mode;
    ta->m_command_str = m_command_str;
    ta->m_file_type_action = m_file_type_action;
    ta->m_options = m_options;
    ta->setRequestParameters( requestParameters() );

    return ta;
}

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

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

int ActivateTextViewModeOp::run( std::shared_ptr< WPUContext > wpu, ActionMessage *msg )
{
    if ( msg->mode == msg->AM_MODE_DNDACTION ) {
        return 0;
    }

    if ( requestParameters() == true ) {
        if ( doconfigure( 1 ) != 0 ) return 0;
    } else {
        m_tactive_side = m_active_side;
        m_tsource_mode = m_source_mode;
        m_tcommand_str = m_command_str;
        m_tfile_type_action = m_file_type_action;
        m_toptions = m_options;
    }
  
    Lister *active_lister = msg->getWorker()->getActiveLister();
    if ( ! active_lister ) return 0;

    Lister *inactive_lister = msg->getWorker()->getOtherLister( active_lister );

    if ( ! inactive_lister ) return 0;

    TextViewMode *tvm = nullptr;
    std::string basedir;

    if ( m_tactive_side ) {
        if ( inactive_lister->getActiveMode() ) {
            basedir = inactive_lister->getActiveMode()->getCurrentDirectory();
        }
        active_lister->switch2Mode( 3 );
        tvm = dynamic_cast< TextViewMode * >( active_lister->getActiveMode() );
    } else {
        if ( active_lister->getActiveMode() ) {
            basedir = active_lister->getActiveMode()->getCurrentDirectory();
        }
        inactive_lister->switch2Mode( 3 );
        tvm = dynamic_cast< TextViewMode * >( inactive_lister->getActiveMode() );
    }

    if ( ! tvm ) return 0;

    switch ( m_tsource_mode ) {
        case TextViewMode::COMMAND_STR:
            tvm->setCommandString( m_tcommand_str, basedir, m_toptions );
            break;
        case TextViewMode::FILE_TYPE_ACTION:
            tvm->setFileTypeAction( m_tfile_type_action, m_toptions );
            break;
        default:
            tvm->setViewActiveFile( m_toptions );
            break;
    }

    return 0;
}

bool ActivateTextViewModeOp::save( Datei *fh )
{
    if ( fh == NULL ) return false;
    fh->configPutPairBool( "activeside", m_active_side );

    switch ( m_source_mode ) {
        case TextViewMode::COMMAND_STR:
            fh->configPutPair( "sourcemode", "commandstring" );
            fh->configPutPairString( "commandstring", m_command_str.c_str() );
            break;
        case TextViewMode::FILE_TYPE_ACTION:
            fh->configPutPair( "sourcemode", "filetypeaction" );
            fh->configPutPairString( "filetypeaction", m_file_type_action.c_str() );
            break;
        default:
            fh->configPutPair( "sourcemode", "activefile" );
            break;
    }

    if ( m_options & TextViewMode::FOLLOW_ACTIVE ) {
        fh->configPutPairBool( "followactive", true );
    }
    if ( m_options & TextViewMode::WATCH_FILE ) {
        fh->configPutPairBool( "watchfile", true );
    }

    fh->configPutPairBool( "requestflags", requestParameters() );
    return true;
}

const char * ActivateTextViewModeOp::getDescription()
{
    return catalog.getLocale( 1500 );
}

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

static void updateVisibility( AContainer *command_ac,
                              AContainer *filetyp_ac,
                              int option )
{
    if ( option == 0 ) {
        command_ac->hide();
        filetyp_ac->hide();
    } else if ( option == 1 ) {
        command_ac->show();
        filetyp_ac->hide();
    } else {
        command_ac->hide();
        filetyp_ac->show();
    }
}

int ActivateTextViewModeOp::doconfigure( int mode )
{
    AGUIX *aguix = Worker::getAGUIX();
    ChooseButton *rfcb = NULL;
    AGMessage *msg;
    int endmode = -1;

    std::string title = AGUIXUtils::formatStringToString( catalog.getLocale( 293 ),
                                                          getDescription() );                                             
    auto win = std::make_unique< AWindow >( aguix, 10, 10, 10, 10, title.c_str(), AWindow::AWINDOW_DIALOG );
    win->create();
  
    AContainer *ac1 = win->setContainer( new AContainer( win.get(), 1, 9 ), true );
    ac1->setMinSpace( 5 );
    ac1->setMaxSpace( 5 );

    ac1->add( new Text( aguix, 0, 0, getDescription() ), 0, 0, AContainer::CO_INCWNR );

    auto active_side_cb = ac1->addWidget( new ChooseButton( aguix, 0, 0, 20, 20, ( m_active_side == true ) ? 1 : 0,
                                                            catalog.getLocale( 1501 ), LABEL_RIGHT, 0 ), 0, 1, AContainer::CO_INCWNR );
    active_side_cb->setBubbleHelpText( catalog.getLocale( 1521 ) );

    AContainer *ac1_2 = ac1->add( new AContainer( win.get(), 2, 1 ), 0, 2 );
    ac1_2->setMinSpace( 5 );
    ac1_2->setMaxSpace( 5 );
    ac1_2->setBorderWidth( 0 );

    ac1_2->add( new Text( aguix, 0, 0, catalog.getLocale( 1502 ) ), 0, 0, AContainer::CO_FIX );
    auto mode_cycb = ac1_2->addWidget( new CycleButton( aguix, 0, 0, 50, 0 ),
                                       1, 0, AContainer::CO_INCW );

    mode_cycb->addOption( catalog.getLocale( 1503 ) );
    mode_cycb->addOption( catalog.getLocale( 1504 ) );
    mode_cycb->addOption( catalog.getLocale( 1505 ) );
    
    switch ( m_source_mode ) {
        case TextViewMode::COMMAND_STR:
            mode_cycb->setOption( 1 );
            break;
        case TextViewMode::FILE_TYPE_ACTION:
            mode_cycb->setOption( 2 );
          break;
        default:
            mode_cycb->setOption( 0 );
            break;
    }
    mode_cycb->resize( mode_cycb->getMaxSize(),
                       mode_cycb->getHeight() );
    mode_cycb->setBubbleHelpText( catalog.getLocale( 1522 ) );
    ac1_2->readLimits();

    AContainer *ac1_3 = ac1->add( new AContainer( win.get(), 4, 1 ), 0, 3 );
    ac1_3->setMinSpace( 0 );
    ac1_3->setMaxSpace( 0 );
    ac1_3->setBorderWidth( 0 );

    ac1_3->add( new Text( aguix, 0, 0, catalog.getLocale( 990 ) ), 0, 0, AContainer::CO_FIX );
    ac1_3->setMaxWidth( 5, 1, 0 );
    auto *command_str_sg = ac1_3->addWidget( new StringGadget( aguix, 0, 0, 50, m_command_str.c_str(), 0 ),
                                             2, 0, AContainer::CO_INCW );
    auto cmd_flag_b = ac1_3->addWidget( new Button( aguix,
                                                    0,
                                                    0,
                                                    "F",
                                                    0 ), 3, 0, AContainer::CO_FIX );
    cmd_flag_b->setBubbleHelpText( catalog.getLocale( 1131 ) );

    AContainer *ac1_4 = ac1->add( new AContainer( win.get(), 4, 1 ), 0, 4 );
    ac1_4->setMinSpace( 0 );
    ac1_4->setMaxSpace( 0 );
    ac1_4->setBorderWidth( 0 );

    ac1_4->add( new Text( aguix, 0, 0, catalog.getLocale( 1506 ) ), 0, 0, AContainer::CO_FIX );
    ac1_4->setMaxWidth( 5, 1, 0 );
    auto *file_type_action_sg = ac1_4->addWidget( new StringGadget( aguix, 0, 0, 50, m_file_type_action.c_str(), 0 ),
                                                  2, 0, AContainer::CO_INCW );
    auto avail_file_type_actions_b = ac1_4->addWidget( new Button( aguix,
                                                                   0,
                                                                   0,
                                                                   "A",
                                                                   0 ), 3, 0, AContainer::CO_FIX );
    avail_file_type_actions_b->setBubbleHelpText( catalog.getLocale( 1507 ) );

    auto follow_active_cb = ac1->addWidget( new ChooseButton( aguix, 0, 0, 20, 20, ( m_options & TextViewMode::FOLLOW_ACTIVE ) ? 1 : 0,
                                                             catalog.getLocale( 1184 ), LABEL_RIGHT, 0 ), 0, 5, AContainer::CO_INCWNR );
    follow_active_cb->setBubbleHelpText( catalog.getLocale( 1523 ) );

    auto watch_file_cb = ac1->addWidget( new ChooseButton( aguix, 0, 0, 20, 20, ( m_options & TextViewMode::WATCH_FILE ) ? 1 : 0,
                                                          catalog.getLocale( 1183 ), LABEL_RIGHT, 0 ), 0, 6, AContainer::CO_INCWNR );
    watch_file_cb->setBubbleHelpText( catalog.getLocale( 1524 ) );

    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, 7, AContainer::CO_INCWNR );
    }

    AContainer *ac1_1 = ac1->add( new AContainer( win.get(), 2, 1 ), 0, 8 );
    ac1_1->setMinSpace( 5 );
    ac1_1->setMaxSpace( -1 );
    ac1_1->setBorderWidth( 0 );

    Button *okb = ac1_1->addWidget( new Button( aguix,
                                                0,
                                                0,
                                                catalog.getLocale( 11 ),
                                                0 ), 0, 0, AContainer::CO_FIX );
    Button *cb = ac1_1->addWidget( new Button( aguix,
                                               0,
                                               0,
                                               catalog.getLocale( 8 ),
                                               0 ), 1, 0, AContainer::CO_FIX );
  
    okb->takeFocus();
    win->setDoTabCycling( true );
    win->contMaximize( true );
    win->show();

    updateVisibility( ac1_3, ac1_4,
                      mode_cycb->getSelectedOption() );

    for ( ; endmode == -1; ) {
        msg = aguix->WaitMessage( win.get() );
        if ( msg ) {
            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 == cmd_flag_b ) {
                        char *tstr = OwnOp::getFlag();
                        if ( tstr != NULL ) {
                            command_str_sg->insertAtCursor( tstr );
                            _freesafe( tstr );
                        }
                    } else if ( msg->button.button == avail_file_type_actions_b ) {
                        std::string action = wconfig->queryNewActionName();
                        if ( ! action.empty() ) {
                            file_type_action_sg->setText( action.c_str() );
                        }
                    }
                    break;
                case AG_KEYPRESSED:
                    if ( win->isParent( msg->key.window, false ) == true ) {
                        switch ( msg->key.key ) {
                            case XK_1:
                                active_side_cb->setState( ( active_side_cb->getState() == true ) ? false : true );
                                break;
                            case XK_2:
                                mode_cycb->setOption( ( mode_cycb->getSelectedOption() + 1 ) % mode_cycb->getNrOfOptions() );
                                updateVisibility( ac1_3, ac1_4,
                                                  mode_cycb->getSelectedOption() );
                                aguix->Flush();
                                break;
                            case XK_3:
                                follow_active_cb->setState( ( follow_active_cb->getState() == true ) ? false : true );
                                break;
                            case XK_4:
                                watch_file_cb->setState( ( watch_file_cb->getState() == true ) ? false : true );
                                break;
                            case XK_Return:
                                if ( cb->getHasFocus() == false ) {
                                    endmode = 0;
                                }
                                break;
                            case XK_Escape:
                                endmode = 1;
                                break;
                        }
                    }
                    break;
                case AG_CYCLEBUTTONCLICKED:
                    if ( msg->cyclebutton.cyclebutton == mode_cycb ) {
                        updateVisibility( ac1_3, ac1_4,
                                          msg->cyclebutton.option );
                        aguix->Flush();
                    }
                    break;
            }
            aguix->ReplyMessage( msg );
        }
    }
  
    if ( endmode == 0 ) {
        // ok
        TextViewMode::source_mode new_source_mode;
        switch ( mode_cycb->getSelectedOption() ) {
            case 1:
                new_source_mode = TextViewMode::COMMAND_STR;
                break;
            case 2:
                new_source_mode = TextViewMode::FILE_TYPE_ACTION;
                break;
            default:
                new_source_mode = TextViewMode::ACTIVE_FILE_OTHER_SIDE;
                break;
        }

        if ( mode == 1 ) {
            m_tactive_side = active_side_cb->getState();
            m_tsource_mode = new_source_mode;
            m_tcommand_str = command_str_sg->getText();
            m_tfile_type_action = file_type_action_sg->getText();

            m_toptions = 0;
            m_toptions |= follow_active_cb->getState() ? TextViewMode::FOLLOW_ACTIVE : 0;
            m_toptions |= watch_file_cb->getState() ? TextViewMode::WATCH_FILE : 0;
        } else {
            m_active_side = active_side_cb->getState();
            m_source_mode = new_source_mode;
            m_command_str = command_str_sg->getText();
            m_file_type_action = file_type_action_sg->getText();
            setRequestParameters( rfcb->getState() );

            m_options = 0;
            m_options |= follow_active_cb->getState() ? TextViewMode::FOLLOW_ACTIVE : 0;
            m_options |= watch_file_cb->getState() ? TextViewMode::WATCH_FILE : 0;
        }
    }
  
    return endmode;
}

void ActivateTextViewModeOp::setActiveSide( bool nv )
{
    m_active_side = nv;
}

void ActivateTextViewModeOp::setSourceMode( TextViewMode::source_mode source_mode )
{
    m_source_mode = source_mode;
}

void ActivateTextViewModeOp::setCommandStr( const std::string &command_str )
{
    m_command_str = command_str;
}

void ActivateTextViewModeOp::setFileTypeAction( const std::string &file_type_action )
{
    m_file_type_action = file_type_action;
}

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

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

void ActivateTextViewModeOp::setOptions( uint32_t options )
{
    m_options = options;
}

void ActivateTextViewModeOp::addOption( uint32_t option )
{
    m_options |= option;
}
