/*
 * location-service.c
 * Copyright (C) 2021 Zwarf <zwarf@mail.de>
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */


#include "location-service.h"

/* GeoClue */
guint timer;

static GClueSimple  *simple       = NULL;
static GClueClient  *client       = NULL;
static GCancellable *cancellabel  = NULL;


static void
stop_location_search (gpointer user_data)
{
  (void) user_data;

  g_clear_object (&client);
  g_clear_object (&simple);
  cancellabel = NULL;
  g_source_remove (timer);
}

static gboolean
on_timeout (gpointer user_data)
{
  (void) user_data;

  g_cancellable_cancel (cancellabel);
  return FALSE;
}

static void
set_user_location (GObject      *source_object,
                   GAsyncResult *res,
                   gpointer user_data)

{
  (void) source_object;
  (void) user_data;
  double latitude;
  double longitude;
  GError *error = NULL;
  static GClueLocation *location; /* How can one free this? */

  simple = gclue_simple_new_with_thresholds_finish (res, &error);

  if (error == NULL)
    {
      location = gclue_simple_get_location (simple);
      latitude = gclue_location_get_latitude (location);
      longitude = gclue_location_get_longitude (location);
      picplanner_set_location (latitude, longitude, PICPLANNER_WINDOW (user_data));
    }
  else
    {
      g_print ("Cannot receive location!\n");
      g_error_free (error);
    }
  stop_location_search (NULL);
}

/*
 * Get the users location
 */
void
get_user_location (GtkButton        *self,
                   gpointer         user_data)
{
  (void) self;

  if (cancellabel == NULL)
    {
      timer = g_timeout_add_seconds (30, on_timeout, NULL);
      cancellabel = g_cancellable_new ();
      gclue_simple_new ("picplanner",
                        GCLUE_ACCURACY_LEVEL_EXACT,
                        cancellabel,
                        set_user_location,
                        user_data);
    }
}