#!/usr/bin/python3
# Copyright 2017 Canonical Ltd
# Author: Iain Lane <iain.lane@canonical.com>

# 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 2 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/>.

import gi
import signal
import sys

gi.require_version('Geoclue', '2.0')
gi.require_version('GeocodeGlib', '1.0')
from gi.repository import Gio, GLib, Geoclue, GeocodeGlib  # noqa: E402

DEFAULT_URL = "https://www.amazon.com/?tag=u1webapp-20"

URLS = {
    "CA": "https://amazon.ca/?tag=u1webapp-ca-20",
    "CN": "https://amazon.cn/?tag=u1webapp-23",
    "DE": "https://amazon.de/?tag=u1webapp-21",
    "ES": "https://amazon.es/?tag=u1webapp-es-21",
    "FR": "https://amazon.fr/?tag=u1webapp-fr-21",
    "GB": "https://amazon.co.uk/?tag=u1webapp-uk-21",
    "IT": "https://amazon.it/?tag=u1webapp-it-21",
    "JP": "https://amazon.co.jp/?tag=u1webapp-22",
}

# 1. Get the location using Geoclue
# 2. Extract the lat, long, accuracy
# 3. Pass this to Geocode
# 4. Reverse geocode it
# 5. Get the country
# 6. Launch the right URL for the country, or the default
# 7. Quit

# If all of this takes more than 5 seconds, launch the default URL and quit -
# something's wrong.


def get_country(latitude, longitude, accuracy, loop):
    geocode = GeocodeGlib.Location.new(latitude,
                                       longitude,
                                       accuracy)

    reverse = GeocodeGlib.Reverse.new_for_location(geocode)
    position = reverse.resolve()
    cc = position.get_country_code()

    Gio.AppInfo.launch_default_for_uri(URLS.get(cc, DEFAULT_URL),
                                       None)

    loop.quit()


def on_simple_ready(o, result, loop):
    try:
        simple = Geoclue.Simple.new_finish(result)
        location = simple.get_location()

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

        get_country(latitude, longitude, accuracy, loop)
    except GLib.Error as e:
        errstr = Gio.dbus_error_get_remote_error(e)
        if errstr == 'org.freedesktop.DBus.Error.AccessDenied':
            print("Access denied - is location available? %s" % e.message,
                  file=sys.stderr)
            launch_default_and_quit(loop)
        else:
            raise


def launch_default_and_quit(loop):
    try:
        Gio.AppInfo.launch_default_for_uri(DEFAULT_URL, None)
    except:
        # not going to do anything about it now
        pass
    finally:
        loop.quit()


def main():
    loop = GLib.MainLoop.new(None, False)
    # make ctrl-c work
    GLib.unix_signal_add(GLib.PRIORITY_HIGH,
                         signal.SIGINT,
                         lambda a: loop.quit(),
                         None)
    Geoclue.Simple.new("com.canonical.launcher.amazon",
                       Geoclue.AccuracyLevel.COUNTRY,
                       None,
                       on_simple_ready,
                       loop)
    # if all else fails
    GLib.timeout_add_seconds(5, launch_default_and_quit, loop)
    loop.run()


if __name__ == "__main__":
    main()
