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

# Standard library imports
import os
import sys

# Third party imports
from qtpy.QtCore import Qt
from qtpy.QtWidgets import (QApplication, QHBoxLayout, QLabel,
                            QListWidget, QVBoxLayout, QFrame)

# Local imports
from anaconda_navigator.config import LOG_FOLDER
from anaconda_navigator.utils.styles import load_style_sheet
from anaconda_navigator.widgets import (ComboBoxBase, SpacerHorizontal,
                                        SpacerVertical, ButtonPrimary)
from anaconda_navigator.widgets.dialogs import DialogBase
from anaconda_navigator.widgets.helperwidgets import LineEditSearch


class ListWidgetLog(QListWidget):
    """Widget used in CSS styling."""

    def __init__(self, *args, **kwargs):
        """Widget used in CSS styling."""
        super(ListWidgetLog, self).__init__(*args, **kwargs)
        self.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.setFocusPolicy(Qt.NoFocus)
        self.setFrameStyle(QFrame.Plain)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setMovement(QListWidget.Static)
        self.setResizeMode(QListWidget.Adjust)
        self.setSelectionMode(self.ExtendedSelection)


class LogViewerDialog(DialogBase):
    """Logger widget."""

    def __init__(self):
        """Logger widget."""
        super(LogViewerDialog, self).__init__()

        # Widgets
        self.label = QLabel('Select log file:')
        self.combobox = ComboBoxBase()
        self.list_logs = ListWidgetLog()
        self.button_copy = ButtonPrimary('Copy')
        self.text_search = LineEditSearch()

        # Widget setup
        self.setWindowTitle('Log Viewer')
        self.setMinimumWidth(600)
        self.setMinimumHeight(400)
        self.text_search.setPlaceholderText("Search...")

        # Layouts
        top_layout = QHBoxLayout()
        top_layout.addWidget(self.label)
        top_layout.addWidget(SpacerHorizontal())
        top_layout.addWidget(self.combobox)
        top_layout.addStretch()
        top_layout.addWidget(SpacerHorizontal())
        top_layout.addWidget(self.text_search)
        top_layout.addWidget(SpacerHorizontal())
        top_layout.addWidget(self.button_copy)
        layout = QVBoxLayout()
        layout.addLayout(top_layout)
        layout.addWidget(SpacerVertical())
        layout.addWidget(self.list_logs)
        self.setLayout(layout)

        # Signals
        self.combobox.currentIndexChanged.connect(self.update_text)
        self.button_copy.clicked.connect(self.copy_item)
        self.text_search.textChanged.connect(self.do_search)

        # Setup()
        self.setup()
        self.update_style_sheet()

    def update_style_sheet(self, style_sheet=None):
        """Update custom CSS stylesheet."""
        if style_sheet is None:
            style_sheet = load_style_sheet()
        self.setStyleSheet(style_sheet)

    def setup(self):
        """Setup widget content."""
        self.combobox.clear()
        logfiles = os.listdir(LOG_FOLDER)

        items = []
        for logf in sorted(logfiles):
            logfilepath = os.path.join(LOG_FOLDER, logf)
            if os.path.isfile(logfilepath):
                items.append(logfilepath)
        self.combobox.addItems(items)

    def do_search(self):
        """Search for text in the selected log file."""
        search = self.text_search.text()
        for i in range(self.list_logs.count()):
            item = self.list_logs.item(i)
            item.setHidden(search not in item.text())

    def update_text(self, index):
        """Update logs based on combobox selection."""
        text = os.path.join(LOG_FOLDER, self.combobox.currentText())
        if os.path.isfile(text):
            with open(text, 'r') as f:
                data = [l for l in f.read().split('\n\n') if l]
            self.list_logs.addItems(data)
            self.list_logs.setCurrentItem(self.list_logs.item(len(data) - 1))

    def copy_item(self):
        """Copy selected item to clipboard."""
        app = QApplication.instance()
        items = self.list_logs.selectedItems()
        if items:
            app.clipboard().setText('\n\n'.join([i.text() for i in items]))


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

    widget = LogViewerDialog()
    widget.show()
    sys.exit(app.exec_())


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