# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2012 David Planella <david.planella@ubuntu.com>
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, 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/>.
### END LICENSE

import gi
gi.require_version('Geoclue', '2.0')
gi.require_version('OsmGpsMap', '1.0')
from gi.repository import Geoclue, GLib, Gtk, OsmGpsMap
from qreator_lib.helpers import get_data_file


class QRCodeLocationGtk(object):
    def __init__(self, qr_code_update_func):
        self.qr_code_update_func = qr_code_update_func
        self.builder = Gtk.Builder()

        self.builder.add_from_file(
            get_data_file('ui', '%s.ui' % ('QrCodeLocation',)))
        self.grid = self.builder.get_object('qr_code_location')

        self.osm = OsmGpsMap.Map()
        self.osm.layer_add(
            OsmGpsMap.MapOsd(show_zoom=True,
                             show_crosshair=True)
        )
        self.osm.set_property("map-source", OsmGpsMap.MapSource_t.OPENSTREETMAP)
        self.osm.set_center_and_zoom(0, 0, 1)

        self.osm.connect("changed", self.on_map_change)

        self.osm.set_hexpand(True)
        self.osm.set_vexpand(True)
        self.grid.attach(self.osm, 0, 0, 1, 1)
        self.grid.show_all()

        self.get_current_location()

    def on_map_change(self, osm):
        self.builder.get_object('lat_entry').set_text(str(self.osm.props.latitude))
        self.builder.get_object('lon_entry').set_text(str(self.osm.props.longitude))

        self.qr_code_update_func(f'geo:{self.osm.props.latitude},{self.osm.props.longitude}')

    def on_activated(self):
        pass

    def on_prepared(self):
        pass

    def get_current_location(self):
        Geoclue.Simple.new(
            'qreator',
            Geoclue.AccuracyLevel.EXACT,
            callback=self.on_current_location_ready
        )

    def on_current_location_ready(self, source, result):
        self.simple = source.new_finish(result)
        location = self.simple.get_location()

        latitude = location.get_property('latitude')
        longitude = location.get_property('longitude')

        if latitude != 0 and longitude != 0:
            self.osm.set_center_and_zoom(latitude, longitude, 15)

        GLib.idle_add(lambda: setattr(self, "simple", None))
