/*
 * 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/>.
 */


/*
 * TODO:
 * Location-Service icon in Gnome is not vanishing when GPS and WIFI is off and
 * location gathering therefore fils.
 */
#include "location/location-service.h"

/* GeoClue */
guint timer;

static GCancellable *cancellable  = NULL;


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

  g_clear_object (&cancellable);
  g_source_remove (timer);

  g_print("Cancel location search\n");
}

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

  g_print ("timeout is canceled: %d\n", g_cancellable_is_cancelled (cancellable));
  g_cancellable_cancel (cancellable);
  g_print ("is cancelded: %d\n", g_cancellable_is_cancelled (cancellable));
  stop_location_search (user_data);

  return FALSE;
}

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

{
  double latitude;
  double longitude;

  GError *error = NULL;
  GClueSimple  *simple       = NULL;
  GClueClient  *client       = NULL;

  static GClueLocation *location; /* How can one free this? */

  (void) source_object;
  (void) user_data;

  simple = gclue_simple_new_finish (res, &error);

  if (error == NULL)
    {
      g_print ("Location received\n");
      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);
    }
  g_clear_object (&client);
  g_clear_object (&simple);
  stop_location_search (user_data);
}

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

  if (cancellable == NULL)
    {
      g_print ("Get users location...\n");
      timer = g_timeout_add_seconds (30, on_timeout, NULL);
      cancellable = g_cancellable_new ();
      gclue_simple_new ("picplanner",
                        GCLUE_ACCURACY_LEVEL_EXACT,
                        cancellable,
                        set_user_location,
                        user_data);
    }
}
