# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Helper widgets."""

from __future__ import (absolute_import, division, print_function,
                        with_statement)

# Third party imports
from qtpy.QtCore import QSize, Qt
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import QHBoxLayout, QLineEdit, QPushButton


class ButtonSearch(QPushButton):
    """Button used for CSS styling."""

    pass


class LineEditSearch(QLineEdit):
    """Lineedit search widget with clear button."""

    def __init__(self, *args, **kwargs):
        """Lineedit search widget with clear button."""
        super(LineEditSearch, self).__init__(*args, **kwargs)
        self._empty = True
        self._show_icons = False
        self.button_icon = ButtonSearch()

        self.button_icon.setDefault(True)
        self.button_icon.setFocusPolicy(Qt.NoFocus)

        layout = QHBoxLayout()
        layout.addWidget(self.button_icon, 0, Qt.AlignRight)
        layout.setSpacing(0)
        layout.addSpacing(2)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # Signals
        self.textEdited.connect(self.update_box)
        self.button_icon.clicked.connect(self.clear_text)

        self.update_box(None)
        self.set_icon_size(16, 16)
        self.setTabOrder(self, self.button_icon)

    def set_icon_size(self, width, height):
        """Set clear button icon size."""
        self.button_icon.setMaximumSize(QSize(width, height))
        self.setStyleSheet('LineEditSearch '
                           '{{padding-right: {0}px;}}'.format(width))

    def set_icon_visibility(self, value):
        """Set clear button visibility."""
        self._show_icons = value
        self.update_box()

    def setProperty(self, name, value):
        """Override Qt method."""
        super(LineEditSearch, self).setProperty(name, value)
        self.style().unpolish(self)
        self.style().polish(self)
        self.update()

    def update_box(self, text=None):
        """Update icon visibility and status."""
        if text:
            if self._show_icons:
                self.button_icon.setIcon(QIcon())
            self.button_icon.setProperty('_remove', True)
        else:
            if self._show_icons:
                self.button_icon.setIcon(QIcon())
            self.button_icon.setProperty('_remove', False)
        self._empty = not bool(text)
        self.button_icon.setDisabled(self._empty)

    def clear_text(self):
        """Clear all text in the line edit."""
        self.setText('')
        self.setFocus()
        self.update_box()

    def update_style_sheet(self, style_sheet=None):
        """Update custom CSS style sheet."""
        if style_sheet is not None:
            self.button_icon.setStyleSheet(style_sheet)

    def keyPressEvent(self, event):
        """Override Qt method."""
        key = event.key()
        if key in [Qt.Key_Escape]:
            self.clear_text()
        else:
            super(LineEditSearch, self).keyPressEvent(event)


# --- Local testing
# -----------------------------------------------------------------------------
def test():  # pragma : no cover
    """Run loca tests."""
    from anaconda_navigator.utils.qthelpers import qapplication

    app = qapplication()
    widget = LineEditSearch()
    widget.show()
    app.exec_()


if __name__ == '__main__':  # pragma : no cover
    test()
