# -*- 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

from gi.repository import Gtk, GObject
from .GtkHelpers import clear_text_entry, show_clear_icon
from qreator_lib.helpers import get_data_file
from qreator_lib.i18n import _
import requests
import json


class IsdgShortener(object):
    # TRANSLATORS: this refers to the is.gd URL shortening service
    name = _("Isgd")

    def __init__(self, url=None):
        self.api_url = "http://is.gd/create.php"
        self.url = url

    def short_url(self):
        self.r = requests.get("{0}?format=simple&url={1}".format(self.api_url,
                                                                 self.url))
        if self.r.content.startswith(b"Error"):
            raise Exception(self.r.content)
        return self.r.content


class TinyUrlShortener(object):
    # TRANSLATORS: this refers to the tinyurl.com URL shortening service
    name = _("TinyUrl")

    def __init__(self, url=None):
        self.api_url = "http://tinyurl.com/api-create.php"
        self.url = url

    def short_url(self):
        self.r = requests.get("{0}?url={1}".format(self.api_url, self.url))
        return self.r.content


class BitlyShortener(object):
    # TRANSLATORS: this refers to the bit.ly URL shortening service
    name = _("Bitly")

    def __init__(self, url=None):
        self.api_url = 'http://api.bit.ly/v3/shorten'
        self.url = url
        self.data = {"login": "",  # TODO
                     "apiKey": "",  # TODO
                     "longUrl": self.url}

    def short_url(self):
        self.r = requests.get(self.api_url, params=self.data)
        self.results = json.loads(self.r.content)
        return self.results["data"]["url"]


class GoogleShortener(object):
    # TRANSLATORS: this refers to the goo.gl URL shortening service
    name = _("Google")

    def __init__(self, url=None):
        self.api_key = "AIzaSyCU_pFNpACW4luWEZRgNnfWMEUdlnZyYQI"
        self.api_url = 'https://www.googleapis.com/urlshortener/v1/url'
        self.url = url
        self.params = {"key": self.api_key,
                       'Content-Type': 'application/json'}
        self.data = {"longUrl": self.url}

    def short_url(self):
        self.r = requests.post(self.api_url, headers=self.params,
                               data=json.dumps(self.data))
        self.results = json.loads(self.r.content)
        return self.results["id"]


SHORTENER_TYPES = [
    IsdgShortener,
    TinyUrlShortener,
    BitlyShortener,
    GoogleShortener,
    ]


class QRCodeURLGtk(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' % ('QrCodeURL',)))
        self.builder.connect_signals(self)
        self.grid = self.builder.get_object('qr_code_url')

        self.messagedialog = self.builder.get_object('messagedialog1')

        self.entry = self.builder.get_object('entryURL')
        self.combobox = self.builder.get_object('comboboxtextProtocol')

        # Initialize placeholder text (we need to do that because due to
        # a Glade bug they are otherwise not marked as translatable)
        self.entry.set_placeholder_text(_('[URL]'))
        self.combobox.set_active(0)

        # Currently four shortener options are available: isdg, google,
        # tinyurl, bitly
        # We are choosing isdg at the moment. Later we will allow to define
        # this in preferences.
        self.Shortener = SHORTENER_TYPES[0]

        # TRANSLATORS: leave '{0}' as it is, it will be replaced by the
        # chosen URL shortening service
        self.builder.get_object("togglebuttonShorten").set_tooltip_text(
            "Use the {0} online service to generate a short URL.".format(
                self.Shortener.name))
        self.builder.get_object("togglebuttonShorten").set_has_tooltip(True)

        self.entryhandler = self.entry.connect("changed",
                                               self.on_entryURL_changed)
        # Moved this signal from the glade file to here, to be able to block
        # it later
        self.iconhandler = self.entry.connect("icon-press",
                                              self.on_entryURL_icon_press)
        self.combobox.connect("changed", self.on_comboboxtextProtocol_changed)

    def on_togglebuttonShorten_toggled(self, widget):
        if widget.get_active():
            # not sensitive while shortener is making the network requests
            # not editable while the shortener button is toggled
            self.entry.set_sensitive(False)
            self.entry.set_editable(False)
            self.entry.handler_block(self.iconhandler)
            self.combobox.set_sensitive(False)
            self.long_address = self.address
            self.entry.set_icon_activatable(Gtk.EntryIconPosition.SECONDARY,
                                            False)
            # If the request takes longer, the interface should in the
            # meantime change to unsensitive button and entry, to show at
            # least some behaviour
            GObject.idle_add(self._shorten_and_display)
        else:
            self.entry.set_has_tooltip(False)
            self.entry.set_text(self.long_address)
            self.entry.set_editable(True)
            self.entry.handler_unblock(self.iconhandler)
            self.combobox.set_sensitive(True)
            self.qr_code_update_func(self.address)
            self.entry.set_icon_activatable(Gtk.EntryIconPosition.SECONDARY,
                                            True)

    def on_messagedialog1_response(self, widget, data=None):
        widget.hide()

    def _reset_shortener(self):
        self.builder.get_object('togglebuttonShorten').set_active(False)

    def _shorten_and_display(self):
        self.entry.set_sensitive(True)
        s = self.Shortener(url=self.address)
        try:
            self.short_address = s.short_url()
        except requests.exceptions.ConnectionError as e:
            # TRANSLATORS: leave '{0}' as it is, it will be replaced by the
            # exception's error message
            self.messagedialog.set_markup(
                _("A network connection error occured: {0}".format(e)))
            self.messagedialog.show()
            GObject.idle_add(self._reset_shortener)
            return
        except Exception as e:
            # TRANSLATORS: leave '{0}' as it is, it will be replaced by the
            # exception's error message
            self.messagedialog.set_markup(
                _("An error occured while trying to shorten the URL: {0}".format(e)))   # pylint: disable=E0501
            self.messagedialog.show()
            GObject.idle_add(self._reset_shortener)
            return
        self.entry.set_tooltip_text(self.long_address)
        self.entry.set_has_tooltip(True)
        self.entry.set_text(self.short_address.decode('utf-8'))
        self.entry.select_region(0, len(self.entry.get_text()))
        self.qr_code_update_func(self.short_address)

    def on_activated(self):
        pass

    def on_prepared(self):
        pass

    def update_url_qr_code(self, protocol=None, www=None):
        if not protocol:
            protocol = self.combobox.get_active_text()
        if not www:
            www = self.entry.get_text()

        if not protocol or www == '':
            return

        self.address = protocol + www

        self.qr_code_update_func(self.address)
        return False

    def on_entryURL_icon_press(self, widget, icon, mouse_button):
        clear_text_entry(widget, icon)

    def check_and_remove_protocol(self, widget):
        """
        Creates a list of protocols (as given by the combobox).
        Checks if the beginning of the text entry is in that list. If so,
        remove the protocol and select the appropriate protocol in the
        combobox.
        """
        for n, protocol in enumerate(
            [mr[0] for mr in self.combobox.get_model()]):
            if widget.get_text().strip().startswith(protocol):
                widget.set_text(widget.get_text().strip()[len(protocol):])
                self.combobox.set_active(n)
                return

    def on_entryURL_changed(self, widget, data=None):
        show_clear_icon(widget)
        self.check_and_remove_protocol(widget)
        self.update_url_qr_code()

    def on_comboboxtextProtocol_changed(self, widget, data=None):
        self.update_url_qr_code(protocol=widget.get_active_text())
