/* chtimecore.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 "chtimecore.hh"
#include "worker_locale.h"
#include "nmcopyopdir.hh"
#include "chtimeorder.hh"
#include "verzeichnis.hh"
#include "aguix/lowlevelfunc.h"
#include "aguix/util.h"
#include "worker.h"
#include "aguix/request.h"
#include "aguix/stringgadget.h"
#include "aguix/button.h"
#include "aguix/choosebutton.h"
#include "aguix/cyclebutton.h"
#include "aguix/awindow.h"
#include "aguix/acontainer.h"
#include "calendar.hh"

ChTimeCore::ChTimeCore( struct chtimeorder *chtimeorder,
                        AGUIX *aguix ) :
    m_chtimeorder( chtimeorder ),
    m_cancel( false ),
    m_aguix( aguix )
{
}

ChTimeCore::~ChTimeCore()
{
}

bool ChTimeCore::getCancel() const
{
    return m_cancel;
}

void ChTimeCore::setCancel( bool nv )
{
    // disallow clearing the flag
    if ( nv == true ) {
        m_cancel = nv;
    }
}

void ChTimeCore::registerFEToChange( const FileEntry &fe,
                                     int row )
{
    m_change_list.push_back( change_base_entry( fe, row ) );
}

ChTimeCore::change_base_entry::change_base_entry( const FileEntry &fe,
                                                  int row ) :
    m_row( row ),
    m_cod( NULL ),
    m_fe( fe )
{
}

ChTimeCore::change_base_entry::~change_base_entry()
{
    delete m_cod;
}

int ChTimeCore::execute()
{
    changetime_info_t ctinfo;

    for ( auto &cbe : m_change_list ) {
        if ( m_cancel ) break;

        if ( worker_changetime( cbe, &ctinfo ) != 0 ) {
            break;
        }
        Worker::pushCommandLog( catalog.getLocale( 1418 ),
                                cbe.entry().fullname,
                                "",
                                cbe.entry().fullname );
    }

    return 0;
}

void ChTimeCore::setPostChangeCallback( std::function< void( const FileEntry &fe, int row,
                                                             change_t res ) > cb )
{
    m_post_cb = cb;
}

int ChTimeCore::worker_changetime( const change_base_entry &ss1,
                                   changetime_info_t *ctinfo )
{
    bool enter, dontChange, skip, cancel;
    int erg;
    changetime_info_t newtime;
    FileEntry *subfe;
    NM_CopyOp_Dir *cod;
  
    if ( ! ctinfo || ! m_chtimeorder ) return -1;

    // do we have to enter this entry?
    enter = false;
    if ( ss1.entry().isDir() == true && m_chtimeorder->recursive == true ) {
        if ( ss1.entry().isLink == false ) enter = true;
    }
  
    // check operation applies to this entry
    dontChange = false;
    if ( ss1.entry().isDir() == true && m_chtimeorder->ondirs == false ) dontChange = true;
    else if ( ss1.entry().isDir() == false && m_chtimeorder->onfiles == false ) dontChange = true;

    skip = cancel = false;

    if ( dontChange == false ) {
        // ask for new owner
        if ( ctinfo->forAll == true ) {
            newtime = *ctinfo;
        } else {
            erg = requestNewTime( ss1.entry(), &newtime );
            if ( erg == 1 ) {
                *ctinfo = newtime;
                ctinfo->forAll = true;
            } else if ( erg == 2 ) {
                skip = true;
            } else if ( erg == 3 ) {
                setCancel( true );
            }
        }
    }
    if ( skip == true ) return 0;
    if ( getCancel() == true ) return 1;

    if ( enter == true && getCancel() == false ) {
        cod = new NM_CopyOp_Dir( &ss1.entry() );
        if ( cod->user_abort == true ) {
            setCancel( true );
        } else if ( cod->ok == true ) {
            for ( Verzeichnis::verz_it subfe_it1 = cod->verz->begin();
                  subfe_it1 != cod->verz->end() && getCancel() == false;
                  subfe_it1++ ) {
                subfe = *subfe_it1;
                if ( strcmp( subfe->name, ".." ) != 0 ) {
                    change_base_entry ss2( *subfe, -1 );
                    if ( worker_changetime( ss2, ctinfo ) != 0 ) {
                        setCancel( true );
                    }
                }
            }
        }
        delete cod;
    }

    if ( dontChange == false ) {
        if ( applyNewTime( ss1, newtime ) != 0 ) setCancel( true );
    }

    return ( getCancel() == true ) ? 1 : 0;
}

ChTimeCore::changetime_info::changetime_info()
{
    forAll = false;
    new_acc_time = 0;
    new_mod_time = 0;
    apply_acc_time = false;
    apply_mod_time = true;
}

int ChTimeCore::applyNewTime( const change_base_entry &ss1,
                              changetime_info_t newtime )
{
    struct utimbuf utb;
    FileEntry fe = ss1.entry();

    fe.readInfos( true );

    utb.actime = ( fe.isLink == true &&
                   fe.isCorrupt == false ) ? fe.dlastaccess() : fe.lastaccess();
    utb.modtime = ( fe.isLink == true &&
                    fe.isCorrupt == false ) ? fe.dlastmod() : fe.lastmod();

    if ( newtime.apply_acc_time ) {
        utb.actime = newtime.new_acc_time;
    }

    if ( newtime.apply_mod_time ) {
        utb.modtime = newtime.new_mod_time;
    }

    if ( worker_utime( fe.fullname, &utb ) != 0 ) {
        char *textstr, *buttonstr;
        int erg;
        
        // error
        buttonstr = (char*)_allocsafe( strlen( catalog.getLocale( 629 ) ) + 1 +
                                       strlen( catalog.getLocale( 8 ) ) + 1 );
        sprintf( buttonstr, "%s|%s", catalog.getLocale( 629 ),
                 catalog.getLocale( 8 ) );
        textstr = (char*)_allocsafe( strlen( catalog.getLocale( 1082 ) ) + strlen( fe.fullname ) + 1 );
        sprintf( textstr, catalog.getLocale( 1082 ), fe.fullname );
        erg = Worker::getRequester()->request( catalog.getLocale( 347 ), textstr, buttonstr );
        _freesafe( buttonstr );
        _freesafe( textstr );
        if ( erg == 1 ) setCancel( true );
    } else {
        if ( ss1.m_row >= 0 && m_post_cb ) {
            m_post_cb( ss1.entry(), ss1.m_row,
                       CHANGE_OK );
        }
    }

    return ( getCancel() == true ) ? 1 : 0;
}

static int checkValidity( ChooseButton *mod_cb,
                           StringGadget *mod_sg,
                           ChooseButton *acc_cb,
                           StringGadget *acc_sg )
{
    if ( mod_cb->getState() ) {
        if ( ! AGUIXUtils::parseStringToTime( mod_sg->getText(), NULL ) ) return 1;
    }

    if ( acc_cb->getState() ) {
        if ( ! AGUIXUtils::parseStringToTime( acc_sg->getText(), NULL ) ) return 2;
    }

    return 0;
}

int ChTimeCore::requestNewTime( const FileEntry &fe,
                                changetime_info_t *return_time )
{
    AWindow *win;
    AGMessage *msg;
    int endmode = -1;

    time_t current_acc_time = ( fe.isLink == true &&
                                fe.isCorrupt == false ) ? fe.dlastaccess() : fe.lastaccess();
    time_t current_mod_time = ( fe.isLink == true &&
                                fe.isCorrupt == false ) ? fe.dlastmod() : fe.lastmod();

    win = new AWindow( m_aguix, 10, 10, 10, 10, catalog.getLocale( 1304 ), AWindow::AWINDOW_DIALOG );
    win->create();
    
    AContainer *ac1 = win->setContainer( new AContainer( win, 1, 4 ), true );
    ac1->setMinSpace( 5 );
    ac1->setMaxSpace( 5 );

    std::string t1 = AGUIXUtils::formatStringToString( catalog.getLocale( 1083 ), fe.fullname );
    
    ac1->add( new Text( m_aguix, 0, 0, t1.c_str() ), 0, 0, AContainer::CO_INCWNR );
    
    AContainer *ac1_1 = ac1->add( new AContainer( win, 5, 2 ), 0, 1 );
    ac1_1->setMinSpace( 5 );
    ac1_1->setMaxSpace( 5 );

    ac1_1->addWidget( new Text( m_aguix, 0, 0, catalog.getLocale( 1084 ) ),
                      0, 0, AContainer::CO_FIX );
    ChooseButton *change_mod_cb = ac1_1->addWidget( new ChooseButton( m_aguix, 0, 0,
                                                                      return_time->apply_mod_time,
                                                                      "", LABEL_LEFT, 0 ),
                                                    1, 0, AContainer::CO_FIXNR );
    StringGadget *mod_time_sg = ac1_1->addWidget( new StringGadget( m_aguix, 0, 0, m_aguix->getTextWidth( "0000-00-00 00:00:00" ) + 16,
                                                                    AGUIXUtils::timeToString( current_mod_time ).c_str(), 0 ),
                                                  2, 0, AContainer::CO_INCW );
    Button *mod_now_b = ac1_1->addWidget( new Button( m_aguix, 0, 0,
                                                      catalog.getLocale( 1102 ), 0 ),
                                          3, 0, AContainer::CO_FIX );
    Button *mod_calendar_b = ac1_1->addWidget( new Button( m_aguix, 0, 0,
                                                           catalog.getLocale( 819 ), 0 ),
                                               4, 0, AContainer::CO_FIX );

    ac1_1->addWidget( new Text( m_aguix, 0, 0, catalog.getLocale( 1085 ) ),
                      0, 1, AContainer::CO_FIX );
    ChooseButton *change_acc_cb = ac1_1->addWidget( new ChooseButton( m_aguix, 0, 0,
                                                                      return_time->apply_acc_time,
                                                                      "", LABEL_LEFT, 0 ),
                                                    1, 1, AContainer::CO_FIXNR );
    StringGadget *acc_time_sg = ac1_1->addWidget( new StringGadget( m_aguix, 0, 0, m_aguix->getTextWidth( "0000-00-00 00:00:00" ) + 16,
                                                                    AGUIXUtils::timeToString( current_acc_time ).c_str(), 0 ),
                                                  2, 1, AContainer::CO_INCW );
    Button *acc_now_b = ac1_1->addWidget( new Button( m_aguix, 0, 0,
                                                      catalog.getLocale( 1102 ), 0 ),
                                          3, 1, AContainer::CO_FIX );
    Button *acc_calendar_b = ac1_1->addWidget( new Button( m_aguix, 0, 0,
                                                           catalog.getLocale( 819 ), 0 ),
                                               4, 1, AContainer::CO_FIX );

    AContainer *ac1_3 = ac1->add( new AContainer( win, 4, 1 ), 0, 3 );
    ac1_3->setMinSpace( 5 );
    ac1_3->setMaxSpace( -1 );
    ac1_3->setBorderWidth( 0 );
    Button *okb =ac1_3->addWidget( new Button( m_aguix,
                                               0,
                                               0,
                                               catalog.getLocale( 11 ),
                                               0 ), 0, 0, AContainer::CO_FIX );
    Button *ok2allb = ac1_3->addWidget( new Button( m_aguix,
                                                    0,
                                                    0,
                                                    catalog.getLocale( 224 ),
                                                    0 ), 1, 0, AContainer::CO_FIX );
    Button *skipb = ac1_3->addWidget( new Button( m_aguix,
                                                  0,
                                                  0,
                                                  catalog.getLocale( 225 ),
                                                  0 ), 2, 0, AContainer::CO_FIX );
    Button *cb = ac1_3->addWidget( new Button( m_aguix,
                                               0,
                                               0,
                                               catalog.getLocale( 8 ),
                                               0 ), 3, 0, AContainer::CO_FIX );
    win->setDoTabCycling( true );
    win->contMaximize( true, true );
    win->show();
  
    for( ; endmode == -1; ) {
        msg = m_aguix->WaitMessage( win );
        if ( msg != NULL ) {
            switch ( msg->type ) {
                case AG_CLOSEWINDOW:
                    if ( msg->closewindow.window == win->getWindow() ) endmode = 3;
                    break;
                case AG_BUTTONCLICKED:
                    if ( msg->button.button == okb ) {
                        endmode = 0;
                    } else if ( msg->button.button == ok2allb ) {
                        endmode = 1;
                    } else if ( msg->button.button == skipb ) {
                        endmode = 2;
                    } else if ( msg->button.button == cb ) {
                        endmode = 3;
                    } else if ( msg->button.button == mod_now_b ) {
                        std::string s1 = AGUIXUtils::timeToString( time( NULL ) );

                        mod_time_sg->setText( s1.c_str() );
                        change_mod_cb->setState( true );
                    } else if ( msg->button.button == acc_now_b ) {
                        std::string s1 = AGUIXUtils::timeToString( time( NULL ) );

                        acc_time_sg->setText( s1.c_str() );
                        change_acc_cb->setState( true );
                    } else if ( msg->button.button == mod_calendar_b ) {
                        Calendar cal( true );
                        time_t tempt;

                        if ( AGUIXUtils::parseStringToTime( mod_time_sg->getText(),
                                                           &tempt ) ) {
                            cal.setInitialDate( tempt );
                        }

                        if ( cal.showCalendar() ) {
                            mod_time_sg->setText( cal.getDate().c_str() );
                            change_mod_cb->setState( true );
                        }
                    } else if ( msg->button.button == acc_calendar_b ) {
                        Calendar cal( true );
                        time_t tempt;

                        if ( AGUIXUtils::parseStringToTime( acc_time_sg->getText(),
                                                            &tempt ) ) {
                            cal.setInitialDate( tempt );
                        }

                        if ( cal.showCalendar() ) {
                            acc_time_sg->setText( cal.getDate().c_str() );
                            change_acc_cb->setState( true );
                        }
                    }
                    break;
                case AG_KEYPRESSED:
                    if ( win->isParent( msg->key.window, false ) == true ) {
                        switch ( msg->key.key ) {
                            case XK_Return:
                            case XK_KP_Enter:
                                if ( ok2allb->getHasFocus() == false &&
                                     skipb->getHasFocus() == false &&
                                     cb->getHasFocus() == false ) {
                                    endmode = 0;
                                }
                                break;
                            case XK_F1:
                                endmode = 0;
                                break;
                            case XK_Escape:
                            case XK_F4:
                                endmode = 3;
                                break;
                            case XK_F2:
                                endmode = 1;
                                break;
                            case XK_F3:
                                endmode = 2;
                                break;
                        }
                    }
                    break;
                case AG_STRINGGADGET_CONTENTCHANGE:
                    if ( msg->stringgadget.sg == mod_time_sg ) {
                        change_mod_cb->setState( true );
                    } else if ( msg->stringgadget.sg == acc_time_sg ) {
                        change_acc_cb->setState( true );
                    }
                    break;
            }
            m_aguix->ReplyMessage( msg );
        }

        if ( endmode == 0 ||
             endmode == 1 ) {
            int res = checkValidity( change_mod_cb,
                                     mod_time_sg,
                                     change_acc_cb,
                                     acc_time_sg );
            if ( res == 1 ) {
                Worker::getRequester()->request( catalog.getLocale( 347 ),
                                                 catalog.getLocale( 1086 ),
                                                 catalog.getLocale( 11 ) );
                endmode = -1;
            } else if ( res == 2 ) {
                Worker::getRequester()->request( catalog.getLocale( 347 ),
                                                 catalog.getLocale( 1087 ),
                                                 catalog.getLocale( 11 ) );
                endmode = -1;
            }
        }
    }
    
    if ( endmode == 0 || endmode == 1 ) {
        // ok
        time_t new_mod_time;
        time_t new_acc_time;

        if ( AGUIXUtils::parseStringToTime( mod_time_sg->getText(),
                                            &new_mod_time ) == true ) {
            return_time->new_mod_time = new_mod_time;
            return_time->apply_mod_time = change_mod_cb->getState();
        }

        if ( AGUIXUtils::parseStringToTime( acc_time_sg->getText(),
                                            &new_acc_time ) == true ) {
            return_time->new_acc_time = new_acc_time;
            return_time->apply_acc_time = change_acc_cb->getState();
        }
    }
    
    delete win;
    
    return endmode;
}
