/* stringmatcher_flexibleregex.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2013-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 "stringmatcher_flexibleregex.hh"
#include "aguix/utf8.hh"
#include <algorithm>
#include <functional>

StringMatcherFlexibleRegEx::StringMatcherFlexibleRegEx() :
    m_match_case_sensitive( false ),
    m_compiled( false ),
#ifdef HAVE_REGEX
    m_groups( NULL ),
#endif
    m_ngroups( 0 ),
    m_flexible_mode_enabled( true )
{
}

StringMatcherFlexibleRegEx::~StringMatcherFlexibleRegEx()
{
#ifdef HAVE_REGEX
    if ( m_compiled ) {
        regfree( &m_compiled_regex );
    }

    free( m_groups );
#endif
}

bool StringMatcherFlexibleRegEx::match( const std::string &str )
{
    return getMatchSegments( str ).size() > 1;
}

void StringMatcherFlexibleRegEx::setMatchString( const std::string &str )
{
    m_match_string = str;
    convertToRegEx();
}

std::string StringMatcherFlexibleRegEx::getMatchString() const
{
    return m_match_string;
}

void StringMatcherFlexibleRegEx::setMatchCaseSensitive( bool nv )
{
    m_match_case_sensitive = nv;
    convertToRegEx();
}

bool StringMatcherFlexibleRegEx::getMatchCaseSensitive() const
{
    return m_match_case_sensitive;
}

std::vector< size_t > StringMatcherFlexibleRegEx::getMatchSegments( const std::string &str )
{
#ifdef HAVE_REGEX
    if ( m_compiled && m_ngroups > 1 ) {
        int erg = regexec( &m_compiled_regex, str.c_str(), m_ngroups, m_groups, 0 );
        if ( erg == 0 ) {
            std::vector< size_t > res;
            regoff_t last_o = 0;
            regmatch_t last_segment = m_groups[1];

            for ( int i = 2; i < m_ngroups; i++ ) {
                if ( m_groups[i].rm_so ==  -1 ) break;

                if ( m_groups[i].rm_so == last_segment.rm_eo ) {
                    // merge matches
                    last_segment.rm_eo = m_groups[i].rm_eo;
                } else {
                    res.push_back( last_segment.rm_so - last_o );
                    res.push_back( last_segment.rm_eo - last_segment.rm_so );
                    last_o = last_segment.rm_eo;
                    last_segment = m_groups[i];
                }
            }

            res.push_back( last_segment.rm_so - last_o );
            res.push_back( last_segment.rm_eo - last_segment.rm_so );
            last_o = last_segment.rm_eo;

            if ( last_o <= (regoff_t)str.length() ) {
                res.push_back( str.length() - last_o );
            }

            return res;
        }
    }
#endif

    return { str.length() };
}

void StringMatcherFlexibleRegEx::convertToRegEx()
{
    m_reg_ex_string.clear();

    int group_count = 1; // one for the complete match

    bool first_char = true;

    for ( const char *cstr = m_match_string.c_str();
          *cstr != '\0'; ) {
        if ( *cstr != '*' ) {
            size_t l = UTF8::getLenOfCharacter( cstr );

            if ( l < 1 ) break;

            if ( first_char || m_flexible_mode_enabled ) {
                m_reg_ex_string += ".*";

                m_reg_ex_string += "(";

                first_char = false;

                group_count++;
            }

            if ( l == 1 ) {
                switch ( *cstr ) {
                    case '.':
                    case '*':
                    case '[':
                    case ']':
                    case '^':
                    case '$':
                    case '(':
                    case ')':
                    case '\\':
                        m_reg_ex_string += "\\";
                        break;
                    default:
                        break;
                }
                m_reg_ex_string += *cstr++;
            } else {
                while ( l > 0 ) {
                    m_reg_ex_string += *cstr++;
                    l--;
                }
            }

            if ( m_flexible_mode_enabled ) {
                m_reg_ex_string += ")";
            }
        } else {
            if ( ! m_flexible_mode_enabled ) {
                if ( first_char == false ) {
                    m_reg_ex_string += ")";

                    first_char = true;
                }
            }

            cstr++;
        }
    }

    if ( ! m_flexible_mode_enabled ) {
        if ( first_char == false ) {
            m_reg_ex_string += ")";
        }
    }

    m_reg_ex_string += ".*";

#ifdef HAVE_REGEX
    if ( m_compiled ) {
        regfree( &m_compiled_regex );
    }

    free( m_groups );
    m_groups = (regmatch_t*)calloc( group_count, sizeof( *m_groups ) );
    m_ngroups = group_count;

    if ( regcomp( &m_compiled_regex,
                  m_reg_ex_string.c_str(),
                  REG_EXTENDED | ( m_match_case_sensitive ? 0 : REG_ICASE ) ) == 0 ) {
        m_compiled = true;
    } else {
        m_compiled = false;
    }
#endif
}

void StringMatcherFlexibleRegEx::setMatchFlexible( bool nv )
{
    m_flexible_mode_enabled = nv;
    convertToRegEx();
}

bool StringMatcherFlexibleRegEx::getMatchFlexible() const
{
    return m_flexible_mode_enabled;
}
