/* changecolumnsop.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2015-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 "changecolumnsop.hh"
#include "listermode.h"
#include "worker.h"
#include "aguix/awindow.h"
#include "aguix/text.h"
#include "aguix/solidbutton.h"
#include "aguix/button.h"
#include "aguix/cyclebutton.h"
#include "aguix/slider.h"
#include "aguix/choosebutton.h"
#include "aguix/fieldlistview.h"
#include "aguix/acontainerbb.h"
#include "aguix/textview.h"
#include <sstream>
#include <algorithm>
#include "datei.h"
#include "worker_locale.h"
#include "virtualdirmode.hh"

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

ChangeColumnsOp::ChangeColumnsOp() : FunctionProto()
{
    hasConfigure = true;
    m_category = FunctionProto::CAT_SETTINGS;
}

ChangeColumnsOp::~ChangeColumnsOp()
{
}

ChangeColumnsOp*
ChangeColumnsOp::duplicate() const
{
    ChangeColumnsOp *ta = new ChangeColumnsOp();
    ta->m_columns = m_columns;
    return ta;
}

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

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

int
ChangeColumnsOp::run( std::shared_ptr< WPUContext > wpu, ActionMessage *msg )
{
    if ( msg->mode != msg->AM_MODE_DNDACTION ) {
        Lister *l1 = msg->getWorker()->getActiveLister();
        if ( l1 ) {
            ListerMode *lm1 = l1->getActiveMode();
            if ( lm1 ) {
                if ( auto vdm = dynamic_cast< VirtualDirMode *>( lm1 ) ) {
                    if ( vdm->getUseCustomColumns() == false ) {
                        vdm->setCustomColumns( m_columns );
                    } else {
                        auto c = vdm->getCustomColumns();
                        if ( c != m_columns ) {
                            vdm->setCustomColumns( m_columns );
                        } else {
                            vdm->unsetCustomColumns();
                        }
                    }
                }
            }
        }
    }
    return 0;
}

bool
ChangeColumnsOp::save( Datei *fh )
{
    if ( fh == NULL ) return false;

    for ( auto &c : m_columns ) {
        switch ( c ) {
            case WorkerTypes::LISTCOL_SIZE:
                fh->configPutInfo( "size", true );
                break;
            case WorkerTypes::LISTCOL_TYPE:
                fh->configPutInfo( "type", true );
                break;
            case WorkerTypes::LISTCOL_PERM:
                fh->configPutInfo( "permission", true );
                break;
            case WorkerTypes::LISTCOL_OWNER:
                fh->configPutInfo( "owner", true );
                break;
            case WorkerTypes::LISTCOL_DEST:
                fh->configPutInfo( "destination", true );
                break;
            case WorkerTypes::LISTCOL_MOD:
                fh->configPutInfo( "modtime", true );
                break;
            case WorkerTypes::LISTCOL_ACC:
                fh->configPutInfo( "acctime", true );
                break;
            case WorkerTypes::LISTCOL_CHANGE:
                fh->configPutInfo( "chgtime", true );
                break;
            case WorkerTypes::LISTCOL_INODE:
                fh->configPutInfo( "inode", true );
                break;
            case WorkerTypes::LISTCOL_NLINK:
                fh->configPutInfo( "nlink", true );
                break;
            case WorkerTypes::LISTCOL_BLOCKS:
                fh->configPutInfo( "blocks", true );
                break;
            case WorkerTypes::LISTCOL_SIZEH:
                fh->configPutInfo( "sizeh", true );
                break;
            case WorkerTypes::LISTCOL_EXTENSION:
                fh->configPutInfo( "extension", true );
                break;
            case WorkerTypes::LISTCOL_CUSTOM_ATTR:
                fh->configPutInfo( "customattribute", true );
                break;
            default:
                fh->configPutInfo( "name", true );
                break;
        }
    }
    
    return true;
}

const char *
ChangeColumnsOp::getDescription()
{
    return catalog.getLocale( 1305 );
}

int
ChangeColumnsOp::configure()
{
    AGUIX *aguix = Worker::getAGUIX();
    AGMessage *msg;
    int endmode = -1;
    char *tstr;
  
    tstr = (char*)_allocsafe( strlen( catalog.getLocale( 293 ) ) +
                              strlen( getDescription() ) + 1 );
    sprintf( tstr, catalog.getLocale( 293 ), getDescription() );
    AWindow *win = new AWindow( aguix, 10, 10, 10, 10, tstr, AWindow::AWINDOW_DIALOG );
    win->create();
    _freesafe(tstr);
    
    unsigned int j, ui;
    int trow;
    const int cincw = AContainer::ACONT_MINH +
        AContainer::ACONT_MINW +
        AContainer::ACONT_MAXH;
    const int cincwnr = cincw +
        AContainer::ACONT_NORESIZE;
    const int cmin = AContainer::ACONT_MINH +
        AContainer::ACONT_MINW;

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

    RefCount<AFontWidth> lencalc( new AFontWidth( aguix, NULL ) );
    auto help_ts = std::make_shared< TextStorageString >( catalog.getLocale( 1120 ), lencalc );
    TextView *help_tv = (TextView*)ac0->add( new TextView( aguix,
                                                           0, 0, 400, 50, "", help_ts ),
                                             0, 0, AContainer::CO_INCW );
    help_tv->setLineWrap( true );
    help_tv->showFrame( false );
    help_tv->maximizeYLines( 10, help_tv->getWidth() );
    ac0->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_1 = ac0->add( new AContainer( win, 3, 1 ), 0, 1 );
    ac1_1->setMinSpace( 5 );
    ac1_1->setMaxSpace( 5 );
    ac1_1->setBorderWidth( 0 );
    AContainer *ac1_1_1 = ac1_1->add( new AContainer( win, 1, 3 ), 0, 0 );
    ac1_1_1->setMinSpace( 0 );
    ac1_1_1->setMaxSpace( 0 );
    ac1_1_1->setBorderWidth( 0 );

    ac1_1_1->add( new Text( aguix, 0, 0, catalog.getLocale( 238 ) ), 0, 0, cincwnr );
    FieldListView *lv1 = ac1_1_1->addWidget( new FieldListView( aguix,
                                                                0, 0,
                                                                100, 50,
                                                                0 ), 0, 1, cmin );
    AContainer *ac1_1_1_1 = ac1_1_1->add( new AContainer( win, 2, 1 ), 0, 2 );
    ac1_1_1_1->setMinSpace( 0 );
    ac1_1_1_1->setMaxSpace( 0 );
    ac1_1_1_1->setBorderWidth( 0 );
    Button *upb = ac1_1_1_1->addWidget( new Button( aguix,
                                                    0, 0,
                                                    catalog.getLocale( 236 ),
                                                    0 ), 0, 0, cincw );
    Button *downb = ac1_1_1_1->addWidget( new Button( aguix,
                                                      0, 0,
                                                      catalog.getLocale( 237 ),
                                                      0 ), 1, 0, cincw );
    lv1->setHBarState(2);
    lv1->setVBarState(2);
    
    AContainer *ac1_1_2 = ac1_1->add( new AContainer( win, 1, 4 ), 1, 0 );
    ac1_1_2->setMinSpace( 5 );
    ac1_1_2->setMaxSpace( -1 );
    ac1_1_2->setBorderWidth( 5 );
    Button *delb = ac1_1_2->addWidget( new Button( aguix,
                                                   0, 0,
                                                   catalog.getLocale(239),
                                                   0 ), 0, 1, cincw );
    Button *insb = ac1_1_2->addWidget( new Button( aguix,
                                                   0, 0,
                                                   catalog.getLocale(240),
                                                   0 ), 0, 2, cincw );

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

    ac1_1_3->add( new Text( aguix, 0, 0, catalog.getLocale( 677 ) ), 0, 0, cincwnr );
    FieldListView *lv2 = ac1_1_3->addWidget(new FieldListView( aguix,
                                                               0, 0,
                                                               lv1->getWidth(),
                                                               50,
                                                               0 ), 0, 1, cmin );
    lv2->setHBarState(2);
    lv2->setVBarState(2);
    
    bool *sels = new bool[WorkerTypes::getAvailListColsSize()];
    for ( j = 0; j < WorkerTypes::getAvailListColsSize(); j++ ) {
        sels[j] = false;
    }
    for ( ui = 0; ui < m_columns.size(); ui++ ) {
        for ( j = 0; j < WorkerTypes::getAvailListColsSize(); j++ ) {
            if ( WorkerTypes::availListCols[j].type == m_columns[ui] ) break;
        }
        if ( j < WorkerTypes::getAvailListColsSize() ) {
            trow = lv1->addRow();
            lv1->setText( trow, 0, catalog.getLocale( WorkerTypes::availListCols[j].catalogid ) );
            lv1->setPreColors( trow, FieldListView::PRECOLOR_ONLYACTIVE );
            sels[j]=true;
        }
    }
    for ( j = 0; j < WorkerTypes::getAvailListColsSize(); j++ ) {
        if ( sels[j] == false ) {
            trow = lv2->addRow();
            lv2->setText( trow, 0, catalog.getLocale( WorkerTypes::availListCols[j].catalogid ) );
            lv2->setPreColors( trow, FieldListView::PRECOLOR_ONLYACTIVE );
        }
    }
    delete [] sels;

    lv1->maximizeX();
    lv2->maximizeX();
    if ( lv1->getWidth() < 100 )
        lv1->resize( 100, lv1->getHeight() );
    lv1->resize( lv1->getWidth(), 10 * lv1->getRowHeight() );

    if ( lv2->getWidth() < 100 )
        lv2->resize( 100, lv2->getHeight() );
    lv2->resize( lv2->getWidth(), 10 * lv2->getRowHeight() );

    ac1_1_1->readLimits();
    ac1_1->readLimits();

    AContainer *ac1_3 = ac0->add( new AContainer( win, 2, 1 ), 0, 2 );
    ac1_3->setMinSpace( 5 );
    ac1_3->setMaxSpace( -1 );
    ac1_3->setBorderWidth( 0 );
    Button *okb =(Button*)ac1_3->add( new Button( aguix,
                                                  0,
                                                  0,
                                                  catalog.getLocale( 11 ),
                                                  0 ), 0, 0, AContainer::CO_FIX );
    Button *cb = (Button*)ac1_3->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;
                    else if ( msg->button.button == upb ) {
                        trow = lv1->getActiveRow();
                        if ( lv1->isValidRow( trow ) == true ) {
                            if ( trow > 0) {
                                lv1->swapRows( trow, trow - 1 );
                                lv1->redraw();
                                lv1->showActive();
                            }
                        }
                    } else if ( msg->button.button == downb ) {
                        trow = lv1->getActiveRow();
                        if ( lv1->isValidRow( trow ) == true ) {
                            if ( trow < ( lv1->getElements() - 1 ) ) {
                                lv1->swapRows( trow, trow + 1 );
                                lv1->redraw();
                                lv1->showActive();
                            }
                        }
                    } else if ( msg->button.button == delb ) {
                        int trow2, trow3;
                        trow = lv1->getActiveRow();
                        if ( lv1->isValidRow( trow ) == true ) {
                            int i1, i2;

                            // first find entry from availlist
                            for ( j = 0, i1 = -1; j < WorkerTypes::getAvailListColsSize(); j++ ) {
                                if ( strcmp( catalog.getLocale( WorkerTypes::availListCols[j].catalogid ),
                                             lv1->getText( trow, 0 ).c_str() ) == 0 ) {
                                    i1 = (int)j;
                                }
                            }
                            // now find insertion position in second LV
                            trow2 = 0;
                            i2=0;
                            int i3;
                            while ( lv2->isValidRow( trow2 ) == true ) {
                                // for each entry search pos in availlist
                                i3 = -1;
                                for ( j = 0; j < WorkerTypes::getAvailListColsSize(); j++ ) {
                                    if ( strcmp( catalog.getLocale( WorkerTypes::availListCols[j].catalogid ),
                                                 lv2->getText( trow2, 0 ).c_str() ) == 0 ) i3 = (int)j;
                                }
                                // for each entry with lower position raise the insertion position
                                if(i3<i1) i2++;
                                trow2++;
                            }
                            trow3 = lv2->insertRow( i2 );
                            lv2->setText( trow3, 0, lv1->getText( trow, 0 ) );
                            lv2->setPreColors( trow3, FieldListView::PRECOLOR_ONLYACTIVE );
                            lv1->deleteRow( trow );
                            lv1->redraw();
                            lv2->redraw();
                        }
                    } else if ( msg->button.button == insb ) {
                        int trow2;
                        trow = lv2->getActiveRow();
                        if ( lv2->isValidRow( trow ) == true ) {
                            trow2 = lv1->addRow();
                            lv1->setText( trow2, 0, lv2->getText( trow, 0 ) );
                            lv1->setPreColors( trow2, FieldListView::PRECOLOR_ONLYACTIVE );
                            lv2->deleteRow( trow );
                            lv1->redraw();
                            lv2->redraw();
                        }
                    }
                case AG_KEYPRESSED:
                    if ( win->isParent( msg->key.window, false ) == true ) {
                        switch ( msg->key.key ) {
                            case XK_Escape:
                                endmode = 1;
                                break;
                        }
                    }
                    break;
                default:
                    break;
            }
            aguix->ReplyMessage( msg );
        }
    }

    if ( endmode == 0 ) {
        // ok
        int trow2;
        std::vector<WorkerTypes::listcol_t> nvc;
        unsigned int j;

        trow2 = 0;
        while ( lv1->isValidRow( trow2 ) == true ) {
            for ( j = 0; j < WorkerTypes::getAvailListColsSize(); j++ ) {
                if ( strcmp( catalog.getLocale( WorkerTypes::availListCols[j].catalogid ),
                             lv1->getText( trow2, 0 ).c_str() ) == 0 ) {
                    nvc.push_back( WorkerTypes::availListCols[j].type );
                }
            }
            trow2++;
        }

        m_columns = nvc;
    }

    delete win;

    return endmode;
}

void ChangeColumnsOp::setColumns( const std::vector<WorkerTypes::listcol_t> &c )
{
    m_columns = c;
}
