/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou 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.
 *
 *  lebiniou 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 lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include "webcam.h"

extern uint8_t hflip, vflip, desired_webcams;
extern char *video_base;


static void
process_token(const char *tok)
{
  gchar **varval = NULL, **vv;

  // printf(">>>>>>>>> token: '%s' <<<<<<<<<<<<<\n", tok);
  varval = g_strsplit(tok, ":", 0);

  vv = varval;

  if (is_equal((const char *)*vv, "webcams")) {
    vv++;
    assert(NULL != *vv);
    desired_webcams = xstrtol(*vv);
    VERBOSE(printf("[E] webcam: grabbing %d device%s\n", desired_webcams, (desired_webcams == 1) ? "" : "s"));
  }
  if (is_equal((const char *)*vv, "device")) {
    vv++;
    assert(NULL != *vv);
    VERBOSE(printf("[E] webcam: device set to %s\n", *vv));
    free(video_base);
    video_base = strdup(*vv);
  } else if (is_equal((const char *)*vv, "hflip")) {
    VERBOSE(printf("[E] webcam: set horizontal flip\n"));
    hflip = !hflip;
  } else if (is_equal((const char *)*vv, "vflip")) {
    VERBOSE(printf("[E] webcam: set vertical flip\n"));
    vflip = !vflip;
  }

  g_strfreev(varval);
}


static void
process_options(const char *options)
{
  gchar **tokens  = NULL, **tok;

  tokens = g_strsplit(options, ",", 0);

  for (tok = tokens ; NULL != *tok; tok++) {
    process_token(*tok);
  }

  g_strfreev(tokens);
}


void
parse_options(void)
{
  char *options = NULL;

  options = getenv("LEBINIOU_WEBCAM");

  if (NULL != options) {
    process_options(options);
  }
}
