/* file_content_checker.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 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 "file_content_checker.hh"
#include "pdatei.h"
#include "worker_locale.h"

void FileContentChecker::setRegex( const std::string &regex,
                                   bool case_sensitive,
                                   loff_t size_limit )
{
    m_regex = regex;
    m_case_sensitive = case_sensitive;
    m_size_limit = size_limit;
}

int FileContentChecker::checkContent( const NWC::FSEntry &file,
                                      std::function< bool (void) > interrupt_test,
                                      std::function< void ( const std::string & ) > feedback_cb,
                                      std::function< void ( const NWC::FSEntry &,
                                                            int ) > result_cb )
{
    if ( interrupt_test() == true ) {
        return 0;
    }

    if ( m_regex.empty() ) {
        result_cb( file, -1 );
        return 1;
    }

    int matches = 0;

    if ( ! file.isReg( true ) ) {
        return 0;
    }

    struct input_buffer inbuf;
    struct line_buffer linebuf;
    PDatei pd;

    inbuf.left = 0;
    inbuf.pos = 0;
    inbuf.pd = &pd;
    inbuf.eof_reached = false;
    inbuf.size_read = 0;

    linebuf.size = sizeof( linebuf.buf ) - 1;
    linebuf.used = 0;

    int current_line = 0;
    int next_line = 0;
    bool newline_found = false;

    if ( pd.open( file.getFullname().c_str() ) != 0 ) {
        return 0;
    }

    feedback_cb( std::string( catalog.getLocale( 748 ) ) + file.getFullname() );
    
    while ( ! interrupt_test() ) {
        // stop if no bytes are left in buffer and eof reached
        if ( inbuf.eof_reached == true && inbuf.left < 1 ) break;
      
        current_line = next_line;
      
        fillLineBuffer( inbuf, linebuf, newline_found );
      
        if ( newline_found == true ) {
            next_line = current_line + 1;
        }

        int line_matches = matchContentLine( linebuf.buf );
        if ( line_matches ) {
            result_cb( file, current_line );
        }

        matches += line_matches;
    }

    return matches;
}

int FileContentChecker::matchContentLine( const char *line )
{
    if ( re.match( m_regex.c_str(), line, ! m_case_sensitive ) == true ) {
        return 1;
    }

    return 0;
}

void FileContentChecker::fillLineBuffer( struct input_buffer &inbuf, struct line_buffer &linebuf, bool &newline_found )
{
    char ch;
    linebuf.used = 0;
    newline_found = false;

    // fill line buffer from buf (load on demand)
    while ( linebuf.used < linebuf.size ) {

        // first read from buf until no byte is left or line buffer is full
        ch = 0;
        while ( inbuf.left > 0 && linebuf.used < linebuf.size ) {
            ch = inbuf.buf[inbuf.pos++];
            inbuf.left--;
            if ( ch != '\n' ) {
                if ( ch != 0 ) // ignore null byte
                    linebuf.buf[linebuf.used++] = ch;
            } else {
                newline_found = true;
                break;
            }
        }
        if ( ch == '\n' || linebuf.used == linebuf.size ) break;

        // no newline found and line buffer not filled means no bytes left in buf
        if ( inbuf.eof_reached == false ) {
            loff_t to_be_read = sizeof(inbuf.buf);
            if ( m_size_limit > 0 ) {
                if ( inbuf.size_read + to_be_read > m_size_limit ) {
                    to_be_read = m_size_limit - inbuf.size_read;
                }

                if ( to_be_read == 0 ) {
                    inbuf.eof_reached = true;
                    break;
                }
            }

            int len = inbuf.pd->read( inbuf.buf, to_be_read );
            if ( len < 1 ) {
                // <0 isn't actually eof but it doesn't matter for content matching
                inbuf.eof_reached = true;
            } else {
                inbuf.left = len;
                inbuf.pos = 0;
                inbuf.size_read += len;
            }
        } else break;
    }
    linebuf.buf[linebuf.used] = '\0';
}
