/*
  This file is part of TALER
  Copyright (C) 2020 Taler Systems SA

  TALER 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 3, or (at your option) any later version.

  TALER 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
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file lang.c
 * @brief Utility functions for parsing and matching RFC 7231 language strings.
 * @author Christian Grothoff
 */
#include "platform.h"
#include "taler_util.h"

/**
 * Check if @a value matches the @a accept_pattern.
 *
 * @param accept_pattern a pattern like "[text|STAR/]*[text|STAR]"
 * @param value the value to match
 * @return true if @a value matches the @a accept_pattern
 */
static bool
pattern_matches (const char *accept_pattern,
                 const char *value)
{
  const char *da;
  const char *dm;

  if (0 == strcmp ("*",
                   accept_pattern))
    return true;
  if (0 == strcmp (value,
                   accept_pattern))
    return true;
  da = strchr (accept_pattern,
               '/');
  dm = strchr (value,
               '/');
  if ( (NULL == da) ||
       (NULL == dm) )
    return false;
  if ( ( (1 == da - accept_pattern) &&
         ('*' == *accept_pattern) ) ||
       ( (da - accept_pattern == dm - value) &&
         (0 == strncasecmp (accept_pattern,
                            value,
                            da - accept_pattern)) ) )
    return pattern_matches (da + 1,
                            dm + 1);
  return false;
}


double
TALER_pattern_matches (const char *pattern,
                       const char *value)
{
  char *p = GNUNET_strdup (pattern);
  char *sptr;
  double r = 0.0;

  for (char *tok = strtok_r (p, ",", &sptr);
       NULL != tok;
       tok = strtok_r (NULL, ",", &sptr))
  {
    char *sptr2;
    char *lp = strtok_r (tok, ";", &sptr2);
    char *qp = strtok_r (NULL, ";", &sptr2);
    double q = 1.0;

    if (NULL == lp)
      continue;
    while (isspace ((int) *lp))
      lp++;
    while (NULL != qp)
    {
      while (isspace ((int) *qp))
        qp++;
      if (1 == sscanf (qp,
                       "q=%lf",
                       &q))
        break;
      qp = strtok_r (NULL, ";", &sptr2);
    }
    if (pattern_matches (lp,
                         value))
      r = GNUNET_MAX (r, q);
  }
  GNUNET_free (p);
  return r;
}


/* end of lang.c */
