// Written by retoor@molodetz.nl

// This source code provides a simple autocomplete functionality by leveraging string list management and pattern matching with escaping
// characters where necessary.

// No external imports or includes other than basic string operations and standard library functions are used in the source code.

// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#ifndef RAUTOCOMPLETE_H
#define RAUTOCOMPLETE_H

#include "rrex4.h"
#include "rstring_list.h"
#define rautocomplete_new rstring_list_new
#define rautocomplete_free rstring_list_free
#define rautocomplete_add rstring_list_add
#define rautocomplete_find rstring_list_find
#define rautocomplete_t rstring_list_t
#define rautocomplete_contains rstring_list_contains

char *r4_escape(char *content) {
    size_t size = strlen(content) * 2 + 1;
    char *escaped = calloc(size, sizeof(char));
    char *espr = escaped;
    char *to_escape = "?*+()[]{}^$\\";
    *espr = '(';
    espr++;
    while (*content) {
        if (strchr(to_escape, *content)) {
            *espr = '\\';
            espr++;
        }
        *espr = *content;
        espr++;
        content++;
    }
    *espr = '.';
    espr++;
    *espr = '+';
    espr++;
    *espr = ')';
    espr++;
    *espr = 0;
    return escaped;
}

char *rautocomplete_find(rstring_list_t *list, char *expr) {
    if (!list->count || !expr || !strlen(expr))
        return NULL;

    char *escaped = r4_escape(expr);

    for (unsigned int i = list->count - 1; i >= 0; i--) {
        char *match = NULL;
        r4_t *r = r4(list->strings[i], escaped);
        if (r->valid && r->match_count == 1) {
            match = strdup(r->matches[0]);
        }
        r4_free(r);
        if (match) {
            free(escaped);
            return match;
        }
    }
    free(escaped);
    return NULL;
}

#endif