/* stringcomparator.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2011-2022 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 "stringcomparator.hh"

enum StringComparator::string_comparator_modes StringComparator::sm_use_mode = StringComparator::STRING_COMPARE_VERSION;

void StringComparator::setStringCompareMode( enum string_comparator_modes nv )
{
    sm_use_mode = nv;
}

enum StringComparator::string_comparator_modes StringComparator::getStringCompareMode()
{
    return sm_use_mode;
}

bool StringComparator::is_equal( const std::string &s1,
                                 const std::string &s2 )
{
    return s1 == s2;
}

int StringComparator::compare( const std::string &s1,
                               const std::string &s2 )
{
    return compare( s1.c_str(), s2.c_str() );
}

int StringComparator::compare( const std::string &s1,
                               const std::string &s2,
                               enum string_comparator_modes mode )
{
    return compare( s1.c_str(), s2.c_str(), mode );
}

bool StringComparator::is_equal( const char *s1,
                                 const char *s2 )
{
    if ( ! s1 || ! s2 ) return false;

    if ( strcmp( s1, s2 ) == 0 ) return true;

    return false;
}

int StringComparator::compare( const char *s1,
                               const char *s2,
                               enum string_comparator_modes mode )
{
    if ( s1 == NULL && s2 == NULL ) return 0;
    if ( s1 == NULL && s2 != NULL ) return 1;
    if ( s1 != NULL && s2 == NULL ) return -1;

#ifdef HAVE_STRVERSCMP
    if ( mode == STRING_COMPARE_VERSION ) {
        return strverscmp( s1, s2 );
    }
#endif

#ifdef HAVE_STRCASECMP
    if ( mode == STRING_COMPARE_NOCASE ||
         mode == STRING_COMPARE_STRICT_NOCASE ) {
        int res = strcasecmp( s1, s2 );

        if ( res != 0 ||
             mode == STRING_COMPARE_STRICT_NOCASE ) {
            return res;
        }

        // fall through to case sensitive comparison
    }
#endif

    return strcmp( s1, s2 );
}

int StringComparator::compare( const char *s1,
                               const char *s2 )
{
    return compare( s1, s2, sm_use_mode );
}
