# -*- 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  # pylint: disable=E0611
from . GtkHelpers import clear_text_entry, show_clear_icon
from qreator_lib.i18n import _
from qreator_lib.helpers import get_data_file


MESSAGE_TYPES = [
    # TRANSLATORS: this refers to a phone call QR code type
    (_("Call"), "tel"),
    # TRANSLATORS: this refers to an SMS message QR code type
    (_("Text Message"), "SMS"),
    ]


class QRCodeSMSGtk(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' % ('QrCodeSMS',)))
        self.grid = self.builder.get_object('qr_code_sms')

        # holds the SMS and Cell selector
        self.messagecombo = self.builder.get_object('comboboxType')
        for t in MESSAGE_TYPES:
            self.messagecombo.append_text(t[0])
        self.messagecombo.set_active(0)
        self.messagecombo.connect(
            "changed", self.on_comboboxType_changed, None)

        self.text = self.builder.get_object('scrolledwindow2')
        # tel is the default message type
        self.text.hide()
        self.builder.get_object('labelMessage').hide()
        self.textbuffer = self.builder.get_object(
            'textviewMessage').get_buffer()
        # TRANSLATORS: this refers to an SMS message
        self.placeholdermessage = _(
            "  [Text message. Some code readers might not support this QR code type]")  # pylint: disable=E0501
        self.textbuffer.set_text(self.placeholdermessage)
        self.messagechanged = self.textbuffer.connect(
            "changed", self.on_textviewMessage_changed, None)

        self.builder.get_object('textviewMessage').connect(
            "focus-in-event", self.on_textviewMessage_focusin, None)
        self.builder.get_object('textviewMessage').connect(
            "focus-out-event", self.on_textviewMessage_focusout, None)

        self.number = self.builder.get_object('entryNumber')
        self.numberchanged = self.number.connect(
            "changed", self.on_entryNumber_changed, None)
        self.number.connect("icon-press", self.on_entryNumber_icon_press)

    # pylint: disable=W0613
    def on_entryNumber_icon_press(self, widget, icon, mouse_button):
        clear_text_entry(widget, icon)

    def on_textviewMessage_focusin(self, widget, data, data2):
        """placeholder text remove"""

        if self.textbuffer.get_text(self.textbuffer.get_start_iter(),
                                    self.textbuffer.get_end_iter(),
                                    False) == self.placeholdermessage:
            self.textbuffer.handler_block(self.messagechanged)
            self.textbuffer.set_text("")
            self.textbuffer.handler_unblock(self.messagechanged)

    def on_textviewMessage_focusout(self, widget, data, data2):
        """placeholder text put back"""
        if self.textbuffer.get_text(self.textbuffer.get_start_iter(),
                                    self.textbuffer.get_end_iter(),
                                    False) == "":
            self.textbuffer.handler_block(self.messagechanged)
            self.textbuffer.set_text(self.placeholdermessage)
            self.textbuffer.handler_unblock(self.messagechanged)

    def on_activated(self):
        pass

    def on_prepared(self):
        pass

    def on_comboboxType_changed(self, widget, data=None):
        if not MESSAGE_TYPES[widget.get_active()][1] == "tel":
            self.text.show()
            self.builder.get_object('labelMessage').show()
        else:
            self.text.hide()
            self.builder.get_object('labelMessage').hide()

        # simply changing the type should not trigger an update on the
        # qrcode
        if not (self.builder.get_object('entryNumber').get_text() == "" and
                self.textbuffer.get_text(self.textbuffer.get_start_iter(),
                                         self.textbuffer.get_end_iter(),
                                         False) == self.placeholdermessage):
            self.on_textviewMessage_changed(self.textbuffer)

    def on_entryNumber_changed(self, widget, data=None):
        # will be used to validate the entered numbers and format them
        # should be replaced in the future with a libphonenumber
        # AsYouTypeFormatter
        show_clear_icon(widget)
        widget.handler_block(self.numberchanged)
        widget.set_text(
            "".join(c for c in widget.get_text() if c in "+0123456789"))
        widget.handler_unblock(self.numberchanged)
        self.on_textviewMessage_changed(self.textbuffer)

    def on_textviewMessage_changed(self, widget, data=None):
        # The SMS data format is not standardized.
        # Possible formats are:
        # sms:number
        # smsto:number
        # sms:number:message
        # smsto:number:message
        # sms:number?body=message

        # the same with capital SMS or SMSTO
        # => we will use SMSTO:number:message
        # based on the tests I did with other readers/scanners
        active_type = self.builder.get_object('comboboxType').get_active()
        ty = MESSAGE_TYPES[active_type][1]
        n = self.builder.get_object('entryNumber').get_text()
        te = widget.get_text(widget.get_start_iter(),
                             widget.get_end_iter(),
                             False)
        if ty == "tel" or te == "" or te == self.placeholdermessage:
            self.qr_code_update_func("{0}:{1}".format(ty, n))
        else:
            self.qr_code_update_func("{0}:{1}:{2}".format(ty, n, te))
