/*
 * LibInputSynth
 * Copyright 2018 Collabora Ltd.
 * Author: Christoph Haag <christoph.haag@collabora.com>
 * SPDX-License-Identifier: MIT
 *
 * This example
 * - moves the cursor from (0,0) to (100,1000)
 * - clicks on (500,500)
 * - writes "hello"
 */

#define GETTEXT_PACKAGE "gtk30"
#include <glib.h>
#include <glib/gi18n-lib.h>

#include <inputsynth.h>
#include <unistd.h>


static gchar *backend = "";

static GOptionEntry options[] =
{
    {"backend", 'b', 0, G_OPTION_ARG_STRING, &backend, "The backend to use", "xdo|xi2"},
    {NULL, 0, 0, 0, 0, 0, 0}
};

static void
_usage(GOptionContext *context)
{
  g_print ("%s\n", g_option_context_get_help (context, TRUE, NULL));
}

int main (int argc, char **argv)
{
    GError *error = NULL;
    GOptionContext *context;

    context = g_option_context_new ("- libinputsynth example");
    g_option_context_add_main_entries (context, options, NULL);

    if (!g_option_context_parse (context, &argc, &argv, &error))
    {
        _usage (context);
    }

  InputSynth *input = NULL;
  if (strncmp (backend, "xdo", 4) == 0)
    {
      input = INPUT_SYNTH (input_synth_new (INPUTSYNTH_BACKEND_XDO));
    }
  else if (strncmp (backend, "xi2", 4) == 0)
    {
      input = INPUT_SYNTH (input_synth_new (INPUTSYNTH_BACKEND_XI2));
    }
  else
    {
      _usage (context);
      return 0;
    }

  if (!input)
    return 1;
  
  g_print ("Using backend: %s\n", backend);


  for (int i = 0; i < 500; i++)
    {
      int y = i * 2;
      int x = i * 2;
      input_synth_move_cursor (input, x, y);
      if (i == 250)
        {
          /* Right click press and release */
          input_synth_click (input, x, y, 3, TRUE);
          usleep (5000);
          input_synth_click (input, x, y, 3, FALSE);
        }
      usleep (5000);
    }

  int char_x = 500;
  int char_y = 500;

  input_synth_move_cursor (input, char_x, char_y);

  input_synth_click (input, char_x, char_y, 3, TRUE);
  usleep (5000);
  input_synth_click (input, char_x, char_y, 3, FALSE);

  usleep (50000);

  input_synth_click (input, char_x, char_y, 3, TRUE);
  usleep (5000);
  input_synth_click (input, char_x, char_y, 3, FALSE);

  usleep (50000);

  input_synth_character (input, 'h');
  usleep (50000);
  input_synth_character (input, 'e');
  usleep (50000);
  input_synth_character (input, 'l');
  usleep (50000);
  input_synth_character (input, 'l');
  usleep (50000);
  input_synth_character (input, 'o');
  usleep (50000);

  g_object_unref (input);

  return 0;
}
