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

"""
"""

# Standard library imports
import os

# Third party imports
from conda_manager.utils.logs import logfile as conda_manager_logfile
from qtpy.QtWidgets import (QComboBox, QHBoxLayout, QLabel, QTextEdit,
                            QVBoxLayout, QFrame)

# Local imports
from anaconda_navigator.utils.qthelpers import qapplication
from anaconda_navigator.utils.styles import load_style_sheet
from anaconda_navigator.config import LOG_FOLDER
from anaconda_navigator.widgets.dialogs import DialogBase


class LogViewerDialog(DialogBase):
    def __init__(self):
        super(LogViewerDialog, self).__init__()

        # Widgets
        self.label = QLabel('Select log file:')
        self.combobox = QComboBox()
        self.text_edit = QTextEdit()

        # Widget setup
        self.text_edit.setFrameStyle(QFrame.Plain)
        self.setWindowTitle('Log Viewer')
        self.setMinimumWidth(600)
        self.setMinimumHeight(400)
        self.text_edit.setReadOnly(True)

        # Layouts
        top_layout = QHBoxLayout()
        top_layout.addWidget(self.label)
        top_layout.addWidget(self.combobox)
        layout = QVBoxLayout()
        layout.addLayout(top_layout)
        layout.addWidget(self.text_edit)
        self.setLayout(layout)

        # Signals
        self.combobox.currentIndexChanged.connect(self.update_text)

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

    def update_style_sheet(self, style_sheet=None):
        if style_sheet is None:
            style_sheet = load_style_sheet()
        self.setStyleSheet(style_sheet)

    def setup(self):
        """
        """
        self.combobox.clear()
        logfiles = [conda_manager_logfile]

        navigator_logfiles = [os.path.join(LOG_FOLDER, fname) for fname in
                              os.listdir(LOG_FOLDER)]

        for logf in sorted(navigator_logfiles) + logfiles:
            if os.path.isfile(logf):
                self.combobox.addItem(logf)

    def update_text(self, index):
        """
        """
        text = self.combobox.currentText()
        if os.path.isfile(text):
            with open(text, 'r') as f:
                data = f.read()
        self.text_edit.setText(data)

    def refresh(self):
        """
        Reload the log files and update the combobox
        """


def test():
    app = qapplication()
    dlg = LogViewerDialog()
    dlg.show()
    app.exec_()


if __name__ == '__main__':
    test()
